Python 如何为 z = f(x, y) 绘制平滑的 2D 颜色图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30509890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:33:39  来源:igfitidea点击:

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

pythonmatplotlibplot

提问by Aeronaelius

I am trying to plot 2D field datausing matplotlib. So basically I want something similar to this:

我正在尝试使用 matplotlib绘制2D 场数据。所以基本上我想要类似的东西:

enter image description here

在此处输入图片说明

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:

在我的实际情况下,我将数据存储在硬盘驱动器上的文件中。然而,为简单起见,请考虑函数 z = f(x, y)。我想要一个平滑的 2D 图,其中 z 使用颜色进行可视化。我使用以下代码行管理绘图:

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 surfaceplots, 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 imshowbut then I have to think in graphiccoordinates where the origin is in the upper left corner.

但是,我获得的情节非常粗糙。有没有一种非常简单的方法来平滑情节?我知道surface绘图可能会出现类似的情况,但是,那些是 3D 的。我可以更改摄像机角度以获得 2D 表示,但我相信有更简单的方法。我也尝试过,imshow但后来我必须考虑graphic原点在左上角的坐标。

Problem solved

问题解决了

I managed to solve my problem using:

我设法使用以下方法解决了我的问题:

plt.imshow(Z,origin='lower',interpolation='bilinear')

plt.imshow(Z,origin='lower',interpolation='bilinear')

采纳答案by wflynny

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:

如果您无法更改网格粒度,请尝试使用imshow,它基本上会将任何 2D 矩阵绘制为图像,其中每个矩阵单元格的值表示构成该像素的颜色。使用您的示例值:

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

enter image description here

在此处输入图片说明

回答by tmdavison

you can use contourf

您可以使用 contourf

plt.contourf(X, Y, Z)

enter image description here

在此处输入图片说明

EDIT:

编辑:

For more levels (smoother colour transitions), you can use more levels (contours)

对于更多级别(更平滑的颜色过渡),您可以使用更多级别(轮廓)

For example:

例如:

plt.contourf(X, Y, Z, 100)

enter image description here

在此处输入图片说明