1

I am trying to plot a 2D finite element mesh using MATPLOTLIB. I have some issues using MAYAVI, so it is not an option.

I would like to know if MATPLOTLIB has any function like "PATCH" in Matlab, which works as follows:

x = [0.0, 0.5, 1.0, 1.0, 1.0, 0.5, 0.0, 0.0];
y = [0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 0.5];
v = [0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 0.5];
patch(x, y, v)

And produces the plot shown below. In a nutshell, I need a simple patch plotting function, which means that I don't want to use any special library to do so. (In case someone asks why I need this: I teach undergrad students and I am using Python3.6 for coding.)

Image created using Matlab PATCH function

1 Answer 1

3

Having as little as 8 points to interpolate between, the resulting plot is not well defined. I.e. a plt.scatter(x,y,c=v) would look like

enter image description here

Using a tricontourf plot like

plt.tricontourf(x,y,v)

would look like

enter image description here

and of course you are free to choose as many levels as you like, e.g. 100

plt.tricontourf(x,y,v,100)

enter image description here

While this looks like the plot in question, I don't think it's well suited for educational purposes, where you would rather teach people about the problem of interpolation and different methods to perform such interpolation.

In that sense, keeping data and plotting seperate is probably a better choice. Hence I would rather do the interpolation first and afterwards display the result. Maybe the Contour plot of irregularly spaced data example is a good starting point here. And an example for the case here could look like

x = [0.0, 0.5, 1.0, 1.0, 1.0, 0.5, 0.0, 0.0];
y = [0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 0.5];
v = [0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 0.5];

import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt

xi = np.linspace(min(x), max(x), 100)
yi = np.linspace(min(y), max(y), 100)

zi = griddata((x, y), v, (xi[None,:], yi[:,None]), method='linear')

plt.pcolormesh(xi,yi,zi)

plt.show()

enter image description here

This uses a pcolormesh plot, which is easier to grasp for displaying the data on the regular grid, as it does not perform any interpolation itself.

Sign up to request clarification or add additional context in comments.

10 Comments

Can I extend this to a 3D mesh?
What's the third dimension then?
Would be something like (x,y,z) and the scalar field value, v.
Sure, I guess you mean something like this example, just with the interpolated values produces in the same manner as in this answer.
No... In your example, "Z" is the "high" of the curve. What I need i something like "triangular_mesh" from MAYAVI.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.