python - 使用 matplotlib.pyplot 绘制多个字典值

标签 python python-2.7 matplotlib

我一直在尝试将列表中存储的值绘制为字典值,但我陷入了困境。下面是字典结构的示例以及我用于迭代键和值的代码:

import matplotlib.pyplot as plt

mydict = {
"A":
[1.0, 0.75, 0.0, 0.25, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.5],
"B":
[1.0, 0.0, 0.0, 0.0, 0.5, 0.6666666666666666, 0.0],
"C":
[0.6666666666666666, 0.3333333333333333, 0.75, 0.25, 0.0, -1, 0.5, 0.75, 0.0, 0.0, 0.0],
"D":
[0.0, 0.0, 0.0, 0.2]}

for k, v in mydict.iteritems():   
    plt.title('Some data for unit: ' + k)
    plt.xlabel('Number of data points')
    plt.ylabel('Some unit')
    plt.figure(k)
    xs = range(0, len(v))
    ys = v
    plt.plot(xs, ys, '-.')
    plt.show

我是一个相对初学者,我可能错过了一些基本和重要的东西,但总是会发生以下情况:第一个图是空的,带有单元 A 的标题,而最后一个图没有标题或标签。所以我猜它模拟了单元 A 的空图,在第二个图中绘制了单元 A 的数据,在图三中绘制了单元 B 的数据,依此类推,直到第五个图,我没想到会在那里,考虑到我的字典只有四个键值对。

我在这里缺少什么?我已经尝试了几个小时,但无法想出解决方案。

非常感谢!

最佳答案

您想要在给图窗赋予标题之前plt.figure()创建它。然后,您需要决定是否要一次显示所有图形(plt.show() 在循环外部),还是逐一显示(在循环内部)。 但是,请确保实际调用 plt.show() - 注意()

for k, v in mydict.iteritems():  
    plt.figure(k) 
    plt.title('Some data for unit: ' + k)
    plt.xlabel('Number of data points')
    plt.ylabel('Some unit')
    xs = range(0, len(v))
    ys = v
    plt.plot(xs, ys, '-.')
    plt.show()

关于python - 使用 matplotlib.pyplot 绘制多个字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53670482/

相关文章:

python - 为什么 matplotlib 开始绘制条形图而不是折线图

python - 试试……除了……除了……: how to avoid repeating code

python 2.7/Windows : How to control position of Tkinter common dialogs?

python - 在 tensorflow 中保存模型

python - if True 和 if False 语句

python - 使用 TensorFlow 初始化非线性回归模型中的偏差项

python-3.x - matplotlib 0.99 Mplot3d 属性错误 : 'list' object has no attribute 'ndim'

python - Matplotlib - 绘制直方图截断条

python - 如何从数据框中找到句子中单词和字符的最大数量?

Python:将str格式转换为可调用方法