【问题标题】:How to plot keys and values from dictionary in histogram如何在直方图中从字典中绘制键和值
【发布时间】:2018-05-22 04:54:25
【问题描述】:

我需要用以下字典绘制直方图

x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}

我需要从 1 到 9 对第一个键进行排序。然后这些值将绘制在直方图中,显示最大概率为 1.0。我已经尝试了以下(加上其他东西)。

import matplotlib.pyplot as plt
import numpy as np

plt.hist(x.keys(), x.values(), color='g', label = "Real distribution")
plt.show()

或者

plt.hist (x, bins = np.arange(9), color = 'g', label = "Real distribution")
plt.show()

或者

fsn_count_ = sorted(fsn_count)

plt.hist (fsn_count_, bins = np.arange(9), color = 'b', label = "Real distribution")
plt.plot ([0] + bf, color = 'g', label = "Benford Model")
plt.xlabel ('Significant number')
plt.ylabel ('Percentage')
plt.xlim (1,9)
plt.ylim (0,1)
plt.legend (bbox_to_anchor = (1, 1), loc="upper right", borderaxespad=0.)
plt.savefig (country_ + '.png')
plt.show ()
plt.clf ()

distribution_sum = sum(bf)
print('The sum of percentage distribution is:', distribution_sum)

【问题讨论】:

  • 请注意,字典不是为有序键设计的。 x.keys() 为您提供x 的所有密钥,但不一定按照您上次调用它时的顺序。
  • 那么,存储这些信息的好方法是什么?我确实需要知道数字五、六... n 出现了多少次,然后绘制它。
  • 首先,您使用的是python 3.x还是python 2.x?
  • 我使用的是 Python 3.x
  • 没关系,Ajax1234 击败了我,并且使用了一种比我要拼凑起来的任何一种更优雅的解决方案。

标签: python dictionary matplotlib plot


【解决方案1】:

从您的评论来看,条形图似乎是显示数据的更好方式。

可以通过将字典的值除以值的总和来找到概率:

import matplotlib.pyplot as plt
import numpy as np

x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}

keys = x.keys()
vals = x.values()

plt.bar(keys, np.divide(list(vals), sum(vals)), label="Real distribution")

plt.ylim(0,1)
plt.ylabel ('Percentage')
plt.xlabel ('Significant number')
plt.xticks(list(keys))
plt.legend (bbox_to_anchor=(1, 1), loc="upper right", borderaxespad=0.)

plt.show()

【讨论】:

    【解决方案2】:

    我很抱歉我的代码非常不符合 Python 风格和怪异。我对 mathplot 或 numpy 不太擅长。

    如果您使用the_keys = list(set(dict.keys())) 获取一组密钥(已订购,因为它是一组。就像我在 cmets 中所说,我在这里做了一些非常丑陋的黑客攻击。)然后您可以执行 the_values = [x[i] for i in the_keys] 来获取按键排序的字典的列表表示。然后用

    绘制它
    plt.hist(the_keys, the_values, color='g', label = "Real distribution")
    plt.show()
    

    【讨论】:

    • by the_keys 你是什么意思? the_keys = list (set("x".keys( ) ) )
    【解决方案3】:

    在绘图前对数据进行排序:

    import matplotlib.pyplot as plt
    import numpy as np
    x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}
    new_x = sorted(x.items(), key=lambda x:x[0])
    plt.hist([i[-1] for i in new_x], normed=True, bins=len(new_x), color='g', label = "Real distribution")
    plt.show()
    

    【讨论】:

    • @Daniel 你能指定你收到什么错误信息吗?
    • 绘制一个空的直方图
    • 它可以工作,但这不是我想要的,我需要在“x”轴中的范围“1”到“9”,而在“y”中需要“0”到“1” " 轴。我会在之前让它工作一些行(不使用字典)
    猜你喜欢
    • 2014-02-07
    • 2014-06-28
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2019-02-22
    • 2014-08-08
    • 1970-01-01
    相关资源
    最近更新 更多