如何绘制轴形状不同的 3D 数据?
How to plot a 3D data whose axis are not the same shape?
我有这样的数据:
[
[1, 2, 3, 4, 5], #x
[6, 7, 8, 9, 0], #y
[[1, 2, 3], [0, 2, 3], [1, 7, 3], [1, 2, 9], [1, 1, 3]] #z is 3 values for each one value in x and y
]
如何在 matplotlib 中 plot/visualize 这样的数据?
我尝试了以下但没有成功:
ax.scatter3D(data[0], data[1], data[2], c=data[2], cmap='Greens');
# and
ax.plot3D(data[0], data[1], data[2], 'gray')
它给我错误:
# first line ==> ValueError: shape mismatch: objects cannot be broadcast to a single shape
# second line ==> ValueError: input operand has more dimensions than allowed by the axis remapping
您需要重塑数据以扩展 x
和 y
以匹配 z
。
使用纯 python:
from itertools import product
a,b,c = zip(*(e for x,y,z in zip(*data) for e in product([x],[y],z)))
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.scatter3D(a, b, c, c=c, cmap='Greens');
使用 numpy:
import numpy as np
x, y = np.repeat(np.array(data[:2]), 3, axis=1)
z = data[2]
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.scatter3D(x, y, z, c=z, cmap='Greens')
输出:
我有这样的数据:
[
[1, 2, 3, 4, 5], #x
[6, 7, 8, 9, 0], #y
[[1, 2, 3], [0, 2, 3], [1, 7, 3], [1, 2, 9], [1, 1, 3]] #z is 3 values for each one value in x and y
]
如何在 matplotlib 中 plot/visualize 这样的数据?
我尝试了以下但没有成功:
ax.scatter3D(data[0], data[1], data[2], c=data[2], cmap='Greens');
# and
ax.plot3D(data[0], data[1], data[2], 'gray')
它给我错误:
# first line ==> ValueError: shape mismatch: objects cannot be broadcast to a single shape
# second line ==> ValueError: input operand has more dimensions than allowed by the axis remapping
您需要重塑数据以扩展 x
和 y
以匹配 z
。
使用纯 python:
from itertools import product
a,b,c = zip(*(e for x,y,z in zip(*data) for e in product([x],[y],z)))
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.scatter3D(a, b, c, c=c, cmap='Greens');
使用 numpy:
import numpy as np
x, y = np.repeat(np.array(data[:2]), 3, axis=1)
z = data[2]
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.scatter3D(x, y, z, c=z, cmap='Greens')
输出: