How to plot a smooth 2D color plot for z = f(x, y)

2020-08-17 06:11发布

问题:

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')

回答1:

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()



回答2:

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)