I am trying to plot 2D field data using matplotlib. So basically I want something similar to this:
In my actual case I have data stored in a file on my harddrive. However for simplicity consider the function z = f(x, y). I want a smooth 2D plot where z is visualised using color. I managed the plotting with the following lines of code:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, 21)
y = np.linspace(-1, 1, 21)
z = np.array([i*i+j*j for j in y for i in x])
X, Y = np.meshgrid(x, y)
Z = z.reshape(21, 21)
plt.pcolor(X, Y, Z)
plt.show()
However, the plot I obtain is very coarse. Is there a very simple way to smooth the plot? I know something similar is possible with surface
plots, however, those are 3D. I could change the camera angle to obtain a 2D representation, but I am convinced there is an easier way. I also tried imshow
but then I have to think in graphic
coordinates where the origin is in the upper left corner.
Problem solved
I managed to solve my problem using:
plt.imshow(Z,origin='lower',interpolation='bilinear')
Select the plot in the Object Manager. In the Property Manager, select the Line tab. Check the Smooth line check box. Adjust the Smooth tension to obtain the desired smoothing.
Smooth Spline Curve with PyPlot:interpolate. make_interp_spline(). We use the given data points to estimate the coefficients for the spline curve, and then we use the coefficients to determine the y-values for very closely spaced x-values to make the curve appear smooth.
If you can't change your mesh granularity, then try to go with imshow
, which will essentially plot any 2D matrix as an image, where the values of each matrix cell represent the color to make that pixel. Using your example values:
In [3]: x = y = np.linspace(-1, 1, 21)
In [4]: z = np.array([i*i+j*j for j in y for i in x])
In [5]: Z = z.reshape(21, 21)
In [7]: plt.imshow(Z, interpolation='bilinear')
Out[7]: <matplotlib.image.AxesImage at 0x7f4864277650>
In [8]: plt.show()
you can use contourf
plt.contourf(X, Y, Z)
EDIT:
For more levels (smoother colour transitions), you can use more levels (contours)
For example:
plt.contourf(X, Y, Z, 100)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With