[英]How to plot a smooth 2D color plot for z = f(x, y)
I am trying to plot 2D field data using matplotlib. 我正在尝试使用matplotlib绘制2D场数据 。 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).
但是为简单起见,考虑函数z = f(x,y)。 I want a smooth 2D plot where z is visualised using color.
我想要一个平滑的2D绘图,其中z使用颜色可视化。 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. 我知道
surface
图可能有类似的东西,然而,那些是3D。 I could change the camera angle to obtain a 2D representation, but I am convinced there is an easier way. 我可以改变相机角度以获得2D表示,但我确信有一种更简单的方法。 I also tried
imshow
but then I have to think in graphic
coordinates where the origin is in the upper left corner. 我也试过
imshow
但是我必须在graphic
坐标中思考原点在左上角。
Problem solved 问题解决了
I managed to solve my problem using: 我设法解决了我的问题:
plt.imshow(Z,origin='lower',interpolation='bilinear')
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. 如果您无法更改网格粒度,请尝试使用
imshow
,这将基本上将任何2D矩阵绘制为图像,其中每个矩阵单元格的值表示制作该像素的颜色。 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
你可以使用
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.