在 matplotlib 中使用 PolyCollection 绘图

Plotting using PolyCollection in matplotlib

我正在尝试在 matplotlib 中绘制 3 维图。我必须在单个 3D 图中绘制四个(或多个)半径的频率与振幅分布。我正在查看 matplotlib.collections 中可用的 PolyCollection 命令,我也查看了示例,但我不知道如何使用现有数据得出绘图。

我拥有的数量的维度是,

频率:4000 x 4, 振幅:4000 x 4, 半径:4

我想绘制类似的东西,

X轴为频率,Y轴为半径,Z轴为振幅。我该如何解决这个问题?

PolyCollection 需要一系列顶点,这与您所需的数据非常匹配。你没有提供任何示例数据,所以我会做一些说明(我的 200 维度将是你的 4000 ....尽管如果你有这么多数据点,我可能会考虑与此不同的情节):

import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d import axes3d
import numpy as np

# These will be (200, 4), (200, 4), and (4)
freq_data = np.linspace(0,300,200)[:,None] * np.ones(4)[None,:]
amp_data = np.random.rand(200*4).reshape((200,4))
rad_data = np.linspace(0,2,4)

verts = []
for irad in range(len(rad_data)):
    # I'm adding a zero amplitude at the beginning and the end to get a nice
    # flat bottom on the polygons
    xs = np.concatenate([[freq_data[0,irad]], freq_data[:,irad], [freq_data[-1,irad]]])
    ys = np.concatenate([[0],amp_data[:,irad],[0]])
    verts.append(list(zip(xs, ys)))

poly = PolyCollection(verts, facecolors = ['r', 'g', 'c', 'y'])
poly.set_alpha(0.7)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# The zdir keyword makes it plot the "z" vertex dimension (radius)
# along the y axis. The zs keyword sets each polygon at the
# correct radius value.
ax.add_collection3d(poly, zs=rad_data, zdir='y')

ax.set_xlim3d(freq_data.min(), freq_data.max())
ax.set_xlabel('Frequency')
ax.set_ylim3d(rad_data.min(), rad_data.max())
ax.set_ylabel('Radius')
ax.set_zlim3d(amp_data.min(), amp_data.max())
ax.set_zlabel('Amplitude')

plt.show()

其中大部分直接来自您提到的示例,我只是明确说明了您的特定数据集所在的位置。这产生了这个情节: