如何在 Matplotlib(Numpy)中生成 MATLAB 图(插值)?
问题描述
我正在尝试遵循网格网格 + 插值的 MATLAB 示例.示例代码位于 HERE一个>.在那个网站上,我正在浏览以下示例:示例 - 在表面上显示非均匀数据.
I am trying to follow a MATLAB example of meshgrid + interpolation. The example code is found HERE. On that site, I am going through the following example: Example – Displaying Nonuniform Data on a Surface.
现在,我想在 Python (Numpy + Matplotlib) 中生成与 MATLAB 中显示的类似的图.这是 MATLAB 生成的图:
Now, I would like to produce a similar plot in Python (Numpy + Matplotlib) to what is shown there in MATLAB. This is the plot that MATLAB produces:
我在 Python 中执行此操作时遇到问题.这是我在 Python 2.7 中的代码和输出:
I am having trouble with doing this in Python. Here is my code and my output in Python 2.7:
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
x = np.random.rand(200)*16 - 8
y = np.random.rand(200)*16 - 8
r = np.sqrt(x**2 + y**2)
z = np.sin(r)/r
xi = np.linspace(min(x),max(x), 100)
yi = np.linspace(min(y),max(y), 200)
X,Y = np.meshgrid(xi,yi)
Z = griddata(x, y, z, X, Y, interp='linear')
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,cmap=cm.jet)
这是我尝试使用 matplotlib 和 NumPy 执行此操作的结果..
Here is the result of my attempt at doing this with matplotlib and NumPy..
有人可以帮我在 matplotlib 中重新创建 MATLAB 图,作为网格图还是曲面图?
Could someone please help me recreate the MATLAB plot in matplotlib, as either a mesh or a surface plot?
解决方案
所以看起来外观的主要差异与matlab默认绘制的行数有关,可以通过增加rstride来调整
和 cstride
.在颜色方面,为了正确缩放颜色图,最好在这种情况下设置限制,vmin
和 vmax
因为当自动设置时,它会使用 Z 的最小值和最大值,但在这种情况下,它们都是 nan
,因此您可以使用 np.nanmin
和 np.nanmax
.
So it seems that the major differences in the look have to do with the default number of lines plotted by matlab, which can be adjusted by increasing rstride
and cstride
. In terms of color, in order for the colormap to be scaled properly it is probably best in this case to set your limits, vmin
and vmax
because when automatically set, it will use the min and max of Z, but in this case, they are both nan
, so you could use np.nanmin
and np.nanmax
.
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
x = np.random.rand(200)*16 - 8
y = np.random.rand(200)*16 - 8
r = np.sqrt(x**2 + y**2)
z = np.sin(r)/r
xi = np.linspace(min(x),max(x), 100)
yi = np.linspace(min(y),max(y), 200)
X,Y = np.meshgrid(xi,yi)
Z = griddata(x, y, z, X, Y, interp='linear')
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=5, cstride=5, cmap=cm.jet, vmin=np.nanmin(Z), vmax=np.nanmax(Z), shade=False)
scat = ax.scatter(x, y, z)
不幸的是,在 matplotlib 中我遇到了一些烦人的重叠/剪切"问题,其中 Axes3d 并不总是正确地确定对象的显示顺序.
In matplotlib unfortunately I get some annoying overlapping/'clipping' problems, where Axes3d doesn't always properly determine the order in which object should be displayed.
相关文章