【问题标题】:Stackplot using list of dictionary values (Python 3.x)Stackplot 使用字典值列表(Python 3.x)
【发布时间】:2015-07-31 19:18:29
【问题描述】:

我正在尝试从字典中制作堆栈图,其中值是 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, and a[5] = 0.15,在值列表的其他索引处以此类推。

我想要一个像here 这样的堆栈图,其中 x 轴上的值列表的索引和 y 轴上该索引处的 a[i] 的值,但无法计算了解如何使该代码或matplotlib example 适应字典。

Python 版本: 3.4

错误(对于我的数据和玩具数据集): TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

建议?

【问题讨论】:

  • 您的字典语法无效。
  • 这是不正确的字典语法。字典写成a = {1:[0.3,0.5,0.7], 2:[0.4,0.6,0.8]}
  • 注意,这是示例中的错字。不是我在真正的字典中遇到的问题。
  • 我是否正确地假设您实际上并不需要 a 的密钥?
  • @jojo 对—— a 的键只是标识符,所以我唯一使用它们的时候是在构建图例。

标签: python python-3.x dictionary matplotlib


【解决方案1】:

更新 - 你得到的错误是因为 matplotlib 对你从dict.values() 得到的视图不满意。请注意,这只是 python 3.x 的问题,因为 python 2.x dict.values() 返回一个列表。你可以通过将视图转换为普通列表来避免这个问题,所以list(dict.values())

这是使用dictmatplotlib example,适用于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()

【讨论】:

  • range() 在 Python 3+ 中替换了 xrange()
  • 即使我删除了 .values,我仍然会收到 TypeError。我使用的一些十进制数字特别长有关系吗?
  • @bradi 请注意,十进制类型 is not supported 因此,如果您将字典 a 转换为仅包含浮点数,则应该没问题。
  • @bradi 将a 中的所有条目转换为浮点数:a = {i: map(lambda x: float(x), a[i]) for i in a}
  • @bradi 问题是 dict.values() 在 python 3.x 中是 view。这就是导致错误的原因。 y = list(d.values()) 会带你到那里(最后:P)。
【解决方案2】:

尚不完全清楚您想要实现什么,但如果我理解您,这应该可行:

import matplotlib.pyplot as plt
a = {1:[0.3,0.5,0.7], 2:[0.4,0.6,0.8], 5:[0.1,0.15,0.20]}
plt.stackplot(a.keys(),a.values())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2017-08-19
    • 2016-01-16
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多