我正在尝试根据字典制作堆栈图,其中值是 0 到 1 之间的浮点列表,列表中值的索引是测量时间 (t1, t2, ...tn)。所有键都具有相同数量的值。例如:
a = {1:[0.3,0.5,0.7], 2:[0.4,0.6,0.8], 5:[0.1,0.15,0.20]}
因此在 t2 处:a[1] = 0.5、a[2] = 0.6 和 a[5] = 0.15
,在值列表的其他索引处依此类推。
我要像 here 这样的堆栈图x 轴上的值列表的索引和 y 轴上该索引处的 a[i] 的值,但无法弄清楚如何调整该代码或 matplotlib example到字典。
Python 版本:3.4
错误(对于我的数据和玩具数据集):
TypeError:输入类型不支持 ufunc 'isfinite',并且根据转换规则 ''safe'' 无法将输入安全地强制转换为任何受支持的类型
建议?
最佳答案
更新 - 您收到的错误是因为 matplotlib 对您从 dict.values()
获得的 View 不满意。请注意,这只是 python 3.x 的问题,因为 python 2.x dict.values()
返回一个列表。您可以通过将 View 转换为普通列表来简单地避免此问题,因此 list(dict.values())
。
这是 matplotlib example使用 dict
,适用于 python 2.x 和 3.x:
import numpy as np
from matplotlib import pyplot as plt
fnx = lambda : np.random.randint(5, 50, 10).astype(np.float64)
d = {i: v for i, v in enumerate(np.row_stack((fnx(), fnx(), fnx())))}
# d looks basically like your a
x = range(len(d[0]))
y = list(d.values()) # d.values() returns a view in python 3.x
fig, ax = plt.subplots()
ax.stackplot(x, y)
plt.show()
关于python - Stackplot 使用字典值列表 (Python 3.x),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31753621/