Python 绘制 3D 彩色图

2 投票
1 回答
2611 浏览
提问于 2025-04-18 02:51

我有三个一维数组,分别存储X值、Y值和Z值。
我想画一个二维图,显示X和Y的关系,并用颜色表示Z的值。

但是每次我尝试运行代码时,都会出现这个错误:

AttributeError: 'list' object has no attribute 'shape'

目前我有:

X=np.array(X)
Y=np.array(Y)
Z=np.array(Z)

fig = pyplot.figure()
ax = fig.add_subplot(111)
p = ax.scatter(X,Y,Z)

我也尝试过:

fig, ax = pyplot.figure()
p = ax.pcolor(X,Y,Z,cmap = cm.RdBu)
cb = fig.colorbar(p,ax=ax)

这两种方法都给我带来了同样的错误。

1 个回答

2

plt.scatter的文档说明了它需要的输入格式是这样的:

matplotlib.pyplot.scatter(x, y, s=20, ...)

这并不是 (x,y,z) 的形式。你把 s(点的大小)设置成了你的 Z 值。如果你想给颜色设置一个“Z”值,应该把它作为 c 参数传入:

import numpy as np
import pylab as plt

# Example points that use a color proportional to the radial distance
N = 2000
X = np.random.normal(size=N)
Y = np.random.normal(size=N)
Z = (X**2+Y**2)**(1/2.0)

plt.scatter(X,Y,c=Z,linewidths=.1)
plt.axis('equal')
plt.show()

enter image description here

撰写回答