绘制由不同长度数组组成的嵌套字典的三维图
我有一个嵌套的字典,长得像这样:
dictionary = {time: {pixels: {intensity}}}
len(time) = 65
len(pixels) = 6/time
len(intensity) = 6/pixel
为了更清楚一点,1个时间值对应着[1,2,3,4,5,6]这些像素值,而每个像素值又有6个强度值。
举个例子:
dictionary = {time1 : {1: array([i11,i12,i13,i14,i15,i16]), 2: array([i21,i22,i23,i24,i25,i26]), 3: array([i31,i32,i33,i34,i35,i36]), 4: array([i41,i42,i43,i44,i45]), 5: array([i51,i52,i53,i54,i55,i56]), 6: array([i61,i62,i63,i64,i65,i66])}}
我想问的是,怎么把这些值画成3D图?时间放在z轴上,强度值和像素值(因为它们都是6个长度)分别放在y轴和x轴上?
以下是我到目前为止尝试过的,但没有成功:
x = []
y = []
z = []
for i in dictionary:
z1 = i
z.append(z1)
x1 = dictionary[i].keys()
x.append(x1)
y1 = dictionary[i].values()
y.append(y1)
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
ax.plot(x, y, zs = 0, zdir='z', label='zs=0,zdir=z')
1 个回答
1
你的 y
是一个列表的列表。如果你使用列出的 for
循环,就很容易发现错误。
修正后的代码:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x, y, z = [], [], []
for tim, pixels in dictionary.items():
for pixel, intensities in pixels.items():
for intensity in intensities:
x.append(intensity)
y.append(pixel)
z.append(tim)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot(x, y, z, zdir='z')
ax.show()
示例用法:
使用这个简单的数据集:
{1: {1: array([11, 12, 13, 14, 15, 16]), 2: array([21, 22, 23, 24, 25, 26]),
3: array([31, 32, 33, 34, 35, 36]), 4: array([41, 42, 43, 44, 45]),
5: array([51, 52, 53, 54, 55, 56]), 6: array([61, 62, 63, 64, 65, 66])},
2: {1: array([71, 72, 73, 74, 75, 76]), 2: array([21, 22, 23, 24, 25, 26]),
3: array([31, 32, 33, 34, 35, 36]), 4: array([41, 42, 43, 44, 45]),
5: array([51, 52, 53, 54, 55, 56]), 6: array([61, 62, 63, 64, 65, 66])}}
这样会得到:
