## Re: [Matplotlib-users] plot a triangular mesh

 Re: [Matplotlib-users] plot a triangular mesh From: John Hunter - 2009-05-22 14:06:12 ```On Thu, May 21, 2009 at 9:31 PM, Ondrej Certik wrote: > Hi, > > I have a set of vertices in 2D as triples (x, y, val), where the x, y > are 2D coordinates and "val" is the scalar value of the finite element > solution, here is an example: > > In [54]: l.get_vertices() > Out[54]: > array([[ 0.00000000e+00, -1.00000000e+00, -2.22396971e-17], > [ 1.00000000e+00, -1.00000000e+00, -1.64798730e-17], > [ -1.00000000e+00, 0.00000000e+00, 8.09899023e-17], > ..., > [ 1.48437500e-01, -1.56250000e-02, 1.62359362e-01], > [ 1.32812500e-01, 0.00000000e+00, 1.56012622e-01], > [ 1.32812500e-01, -1.56250000e-02, 1.50562411e-01]]) > > > and I also have a set of triangles that connect those points, here is > an example: > > In [55]: l.get_triangles() > Out[55]: > array([[ 3, 5448, 29], > [ 27, 5445, 28], > [ 29, 28, 26], > ..., > [5499, 5498, 5479], > [5510, 5493, 5491], > [5513, 5508, 5491]], dtype=int32) > > > The triangles define the 2D domain. What is the best way to get this > plotted with mpl? Should I write a loop using the "plot" command, or > is there a better alternative? So far, I am using the contour command > and I feed it just with the vertices, here is the code: The best way is to define your triangles as an n length list of triangle vertices verts = [ ( (x00, y00), (x01, y01), (x02, y02)), (x10, y10), (x11, y11), (x12, y12)), ... ] and have an equal length array of intensities for color mapping. vals = np.array(N_color_intensities) Then create a PolyCollection: import matplotlib.cm as cm import matplotlib.collections as collections col = collections.PolyCollection(verts) col.set_array(val) col.set_cmap(cm.hot) ax.add_collection(col) add_collection doesn't get the autoscaling limits, if I recall correctly, so you will probably want to do ax.set_xlim(xmin, xmax) ax.set_ylim(ymin,. ymax) See also: http://matplotlib.sourceforge.net/api/collections_api.html#matplotlib.collections.PolyCollection http://matplotlib.sourceforge.net/search.html?q=codex+PolyCollection Unfortunately, we do not currently have support for interpolating between adjacent polys in a PolyCollection, so the result may not look as nice as mayavis. JDH ```