简体   繁体   English

使用 meshgrid 将 X,Y,Z 三元组转换为三个 2D arrays for surface plot in matplotlib

[英]Using meshgrid to convert X,Y,Z triplet to three 2D arrays for surface plot in matplotlib

I'm new to Python so please be patient.我是 Python 的新手,请耐心等待。 I appreciate any help!感谢您的帮助!

What I have: three 1D lists ( xr, yr, zr ), one containing x-values, the other two y- and z-values我有什么:三个一维列表( xr, yr, zr ),一个包含 x 值,另外两个 y 和 z 值
What I want to do: create a 3D contour plot in matplotlib我想做的:在 matplotlib 中创建一个 3D 轮廓 plot

I realized that I need to convert the three 1D lists into three 2D lists, by using the meshgrid function.我意识到我需要使用meshgrid function 将三个一维列表转换为三个二维列表。

Here's what I have so far:这是我到目前为止所拥有的:

xr = np.asarray(xr) 
yr = np.asarray(yr)
zr = np.asarray(zr)

X, Y = np.meshgrid(xr,yr)
znew = np.array([zr for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = znew.reshape(X.shape)

Running this gives me the following error (for the last line I entered above):运行它会给我以下错误(对于我在上面输入的最后一行):

 total size of new array must be unchanged

I went digging around stackoverflow, and tried using suggestions from people having similar problems.我深入研究了 stackoverflow,并尝试使用有类似问题的人的建议。 Here are the errors I get from each of those suggestions:以下是我从这些建议中得到的错误:

Changing the last line to:将最后一行更改为:

Z = znew.reshape(X.shape[0])

Gives the same error.给出相同的错误。

Changing the last line to:将最后一行更改为:

Z = znew.reshape(X.shape[0], len(znew))

Gives the error:给出错误:

Shape of x does not match that of z: found (294, 294) instead of (294, 86436).

Changing it to:将其更改为:

Z = znew.reshape(X.shape, len(znew))

Gives the error:给出错误:

an integer is required

Any ideas?有任何想法吗?

Well,sample code below works for me好吧,下面的示例代码对我有用

import numpy as np
import matplotlib.pyplot as plt

xr = np.linspace(-20, 20, 100)
yr = np.linspace(-25, 25, 110)
X, Y = np.meshgrid(xr, yr)

#Z = 4*X**2 + Y**2

zr = []
for i in range(0, 110):
    y = -25.0 + (50./110.)*float(i)
    for k in range(0, 100):
        x = -20.0 + (40./100.)*float(k)

        v = 4.0*x*x + y*y

        zr.append(v)

Z = np.reshape(zr, X.shape)

print(X.shape)
print(Y.shape)
print(Z.shape)

plt.contour(X, Y, Z)
plt.show()

TL;DR长话短说

import matplotlib.pyplot as plt
import numpy as np

def get_data_for_mpl(X, Y, Z):
    result_x = np.unique(X)
    result_y = np.unique(Y)
    result_z = np.zeros((len(result_x), len(result_y)))
    # result_z[:] = np.nan

    for x, y, z in zip(X, Y, Z):
        i = np.searchsorted(result_x, x)
        j = np.searchsorted(result_y, y)
        result_z[i, j] = z

    return result_x, result_y, result_z


xr, yr, zr = np.genfromtxt('data.txt', unpack=True)

plt.contourf(*get_data_for_mpl(xr, yr, zr), 100)
plt.show()

Detailed answer详细解答

At the beginning, you need to find out for which values of x and y the graph is being plotted.开始时,您需要找出绘制图形的xy值。 This can be done using the numpy.unique function:这可以使用numpy.unique function 来完成:

result_x = numpy.unique(X)
result_y = numpy.unique(Y)

Next, you need to create a numpy.ndarray with function values for each point (x, y) from zip(X, Y) :接下来,您需要为zip(X, Y)中的每个点(x, y)创建一个包含numpy.ndarray个值的 numpy.ndarray:

result_z = numpy.zeros((len(result_x), len(result_y)))

for x, y, z in zip(X, Y, Z):
    i = search(result_x, x)
    j = search(result_y, y)
    result_z[i, j] = z

If the array is sorted, then the search in it can be performed not in linear time, but in logarithmic time, so it is enough to use the numpy.searchsorted function to search.如果数组是排序的,那么里面的查找可以不是线性时间,而是对数时间,所以用numpy.searchsorted function来查找就可以了。 but to use it, the arrays result_x and result_y must be sorted.但要使用它,必须对 arrays result_xresult_y进行排序。 Fortunately, sorting is part of the numpy.unique method and there are no additional actions to do.幸运的是,排序是numpy.unique方法的一部分,无需执行其他操作。 It is enough to replace the search (this method is not implemented anywhere and is given simply as an intermediate step) method with np.searchsorted .np.searchsorted替换search (此方法未在任何地方实现,只是作为中间步骤给出)方法就足够了。

Finally, to get the desired image, it is enough to call the matplotlib.pyplot.contour or matplotlib.pyplot.contourf method.最后,要获得想要的图像,只需调用matplotlib.pyplot.contourmatplotlib.pyplot.contourf方法即可。

If the function value does not exist for (x, y) for all x from result_x and all y from result_y , and you just want to not draw anything, then it is enough to replace the missing values with NaN.如果 result_x 中的所有xresult_x中的所有y(x, y)值不存在result_y值,而您只想不绘制任何内容,则用 NaN 替换缺失值就足够了。 Or, more simply, create result_z as numpy.ndarray` from NaN and then fill it in:或者,更简单地说,从 NaN 创建result_z为 numpy.ndarray`,然后填写:

result_z = numpy.zeros((len(result_x), len(result_y)))
result_z[:] = numpy.nan

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我收到错误Z时,如何使用python中的三个1D数组绘制3D表面图,必须在2维中。 如何将其转换为2D数组? - How to plot a 3D surface Plot using three 1D arrays in python as I am getting an error Z must be in 2 dimensional. How to convert it into 2D array? 来自 x、y、z 值的 matplotlib 2D 图 - matplotlib 2D plot from x,y,z values 给定 x,y,z 坐标的数据,我将如何在 Matplotlib 中制作 3D 表面 plot? - How would I make a 3D surface plot in Matplotlib given this data of x,y,z coordinates? 如何使用 matplotlib 创建 3d 曲面 plot 当 x 和 y 表示为 1d ZA3CCBC4F9D0CE2D71D971 - How to create a 3d surface plot with matplotlib when x and y are stated as 1d arrays? Matplotlib plot_surface:如何将一维数组转换为所需的二维输入? - Matplotlib plot_surface: How to convert 1D arrays to required 2D input? 表面 Plot 的 3D Arrays 使用 matplotlib - Surface Plot of 3D Arrays using matplotlib 如何从三个数组创建x,y,z坐标,其中x和y是使用meshgrid生成的,而z取决于x? - How do I create x,y,z coordinates from three arrays, where x and y are generated with meshgrid and z is dependent on x? python-将x,y,z值映射到2D表面数据 - python - map x, y, z values to 2D surface data 参数化3D曲面图,颜色取决于(x,y,z) - Parametric 3D Surface Plot with color depending on (x,y,z) 使用 Matplotlib a*y + b*x + c 绘制 3D 曲面 - Plot 3D surface with Matplotlib a*y + b*x + c
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM