【问题标题】:Plotting histogram from dictionary Python从字典Python中绘制直方图
【发布时间】:2014-05-23 16:48:58
【问题描述】:

我有一个字典,每个键都有一个值。

我想将此字典绘制为带有matplotlib 的条形图,为每个条形设置不同的颜色,并找到一种将长字符串用作易读标签的方法。

X = np.arange(len(dictionay))
pl.bar(X, dictionay.values(), align='center', width=0.5)
pl.xticks(X, dictionay.keys())
pl.xticks(rotation=20)
ymax = max(dictionay.values()) + 1
pl.ylim(0, ymax)
pl.show()

结果:

我的钥匙很长,所以我们什么都看不清楚!此外,最好让这个图按 y 值排序。我知道字典无法排序,所以我可以浏览一下列表吗?

有什么想法吗?

谢谢

【问题讨论】:

  • 您希望如何对键进行排序?你真的需要每一个的完整长度吗?
  • 您的问题是什么?好像是你做的?你的问题是“如何在我的字典中使用较短的键?”我不明白...你当然可以给一个排序列表...
  • 两种可能性是:1)如何在栏旁边的空白处垂直绘制字符串,2)当将鼠标指针悬停在栏上时,将字符串作为弹出窗口。这些都行吗?

标签: python matplotlib


【解决方案1】:

我想用 matplotlib 绘制这个字典,设置一个不同的 每个键的颜色并找到一种方法来绘制很长的键 字符串...此外,如果对这个情节进行排序,那就太好了。

不幸的是,我能够绘制长字符串的最佳方法是截断它们。我随意选择了 15 个字符作为最大长度,你可以使用任何你认为合适的长度。

以下代码定义了一个字典 (Dictionary),创建了一个按值从大到小的排序键和排序值的列表,并截断了太长而无法很好显示的键。绘制条形图时,一次绘制一个条形图,因此可以为条形图设置单独的颜色。颜色是通过迭代开头定义的元组 (Colors) 来选择的。

import numpy as np
import matplotlib.pyplot as plt

Dictionary = {"A":3,"C":5,"B":2,"D":3,"E":4,
              "A very long key that will be truncated when it is graphed":1}
Dictionary_Length = len(Dictionary)
Max_Key_Length = 15
Sorted_Dict_Values = sorted(Dictionary.values(), reverse=True)
Sorted_Dict_Keys = sorted(Dictionary, key=Dictionary.get, reverse=True)
for i in range(0,Dictionary_Length):
    Key = Sorted_Dict_Keys[i]
    Key = Key[:Max_Key_Length]
    Sorted_Dict_Keys[i] = Key
X = np.arange(Dictionary_Length)
Colors = ('b','g','r','c')  # blue, green, red, cyan

Figure = plt.figure()
Axis = Figure.add_subplot(1,1,1)
for i in range(0,Dictionary_Length):
    Axis.bar(X[i], Sorted_Dict_Values[i], align='center',width=0.5, color=Colors[i%len(Colors)])

Axis.set_xticks(X)
xtickNames = Axis.set_xticklabels(Sorted_Dict_Keys)
plt.setp(Sorted_Dict_Keys)
plt.xticks(rotation=20)
ymax = max(Sorted_Dict_Values) + 1
plt.ylim(0,ymax)

plt.show()

输出图:

【讨论】:

    猜你喜欢
    • 2014-06-28
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2018-05-23
    • 2011-08-21
    • 1970-01-01
    • 2015-07-21
    相关资源
    最近更新 更多