使用meshgrid将X,Y,Z三元组转换为三个2D数组以在matplotlib中进行表面绘图 [英] Using meshgrid to convert X,Y,Z triplet to three 2D arrays for surface plot in matplotlib

查看:311
本文介绍了使用meshgrid将X,Y,Z三元组转换为三个2D数组以在matplotlib中进行表面绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,所以请耐心等待.感谢您的帮助!

I'm new to Python so please be patient. I appreciate any help!

我所拥有的:三个一维列表( xr,yr,zr ),一个包含x值,另外两个包含y和z值
我想做的事情:在matplotlib中创建3D等高线图

What I have: three 1D lists (xr, yr, zr), one containing x-values, the other two y- and z-values
What I want to do: create a 3D contour plot in matplotlib

我意识到我需要使用 meshgrid 函数将三个1D列表转换为三个2D列表.

I realized that I need to convert the three 1D lists into three 2D lists, by using the 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

我深入研究了stackoverflow,并尝试使用有类似问题的人的建议.这是我从这些建议中得到的错误:

I went digging around stackoverflow, and tried using suggestions from people having similar problems. Here are the errors I get from each of those suggestions:

将最后一行更改为:

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

给出相同的错误.

将最后一行更改为:

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

给出错误:

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

将其更改为:

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

给出错误:

an integer is required

有什么想法吗?

推荐答案

下面的示例代码对我有用

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

这篇关于使用meshgrid将X,Y,Z三元组转换为三个2D数组以在matplotlib中进行表面绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆