【问题标题】:Python Histogram with monthly frequencies具有每月频率的 Python 直方图
【发布时间】:2018-06-20 12:47:07
【问题描述】:

我需要使用 matplotlib 在 Python 中制作直方图。我的数据是每月发生事件的频率元组,如下所示,其中 x 轴应显示月份,y 轴应显示频率。有人可以帮忙吗?

[('Jun-07', 10),
 ('Jun-08', 15),
 ('Jun-09', 16),
 ('Nov-07', 17),
 ('Nov-08', 16),
 ('Nov-09', 14),
 ('May-11', 16),
 ('May-10', 18),
 ('May-13', 14),
 ('May-12', 14),
 ('May-14', 12),
 ('Jun-14', 10),
 ('Jun-11', 14),
 ('Jun-10', 19),
 ('Jun-13', 13),
 ('Jun-12', 14),
 ('Feb-09', 10),
 ('Nov-14', 10),
 ('Nov-13', 12),
 ('Nov-12', 13)]

【问题讨论】:

  • 到目前为止你有没有尝试过?你能给我们看看吗?
  • 是的,我能够从系列中制作条形图。

标签: python matplotlib histogram


【解决方案1】:

如果您想要相对于月份的直方图,您应该执行以下操作:

import calendar
dmonths = dict((v,k) for k,v in enumerate(calendar.month_abbr))

import numpy as np
from matplotlib import pyplot as plt

list1 = [('Jun-07', 10),
 ('Jun-08', 15),
 ('Jun-09', 16),
 ('Nov-07', 17),
 ('Nov-08', 16),
 ('Nov-09', 14),
 ('May-11', 16),
 ('May-10', 18),
 ('May-13', 14),
 ('May-12', 14),
 ('May-14', 12),
 ('Jun-14', 10),
 ('Jun-11', 14),
 ('Jun-10', 19),
 ('Jun-13', 13),
 ('Jun-12', 14),
 ('Feb-09', 10),
 ('Nov-14', 10),
 ('Nov-13', 12),
 ('Nov-12', 13)]

list2 = [dmonths[x[0][:3]] for x in list1]
list3 = [x[1] for x in list1]

plt.hist(np.array(list2), bins=np.array(range(1,12)), weights=np.array(list3))

前两行给出了一个从月份到整数的查找表。之后,您只需要提取月份的名称,将它们转换为整数,并以值作为权重绘制直方图。

【讨论】:

    【解决方案2】:
    import matplotlib.pyplot as plt
    
    def histogram():
        set_list = set(link_list)
        return [(idx, link_list.count(idx)) for idx in set_list]
    
    xx, yy = [datetime.strptime(idx[0],'%b-%y') for idx in his_sorted],
             [idx[1] for idx in his_sorted]
    plt.bar(xx, yy, width = 50)
    

    【讨论】:

    • link_listhis_sorted 没有定义,也没有使用你写的函数histogram()。此外,我认为您需要导入 datetime 模块
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 2017-04-23
    • 2020-03-28
    • 2017-11-15
    • 2017-04-11
    • 1970-01-01
    相关资源
    最近更新 更多