【问题标题】:Put value at centre of bins for histogram将值放在柱状图的中心
【发布时间】:2015-09-08 08:47:45
【问题描述】:

我有以下代码来绘制直方图。 time_new 中的值是发生某事的时间。

    time_new=[9, 23, 19, 9, 1, 2, 19, 5, 4, 20, 23, 10, 20, 5, 21, 17, 4, 13, 8, 13, 6, 19, 9, 14, 9, 10, 23, 19, 23, 20, 19, 6, 5, 24, 20, 19, 15, 14, 19, 14, 15, 21]

    hour_list = time_new
    print hour_list
    numbers=[x for x in xrange(0,24)]
    labels=map(lambda x: str(x), numbers)
    plt.xticks(numbers, labels)
    plt.xlim(0,24)
    pdb.set_trace()
    plt.hist(hour_list,bins=24)
    plt.show()

这会生成一个直方图,但是这些 bin 没有按照我的意愿对齐。我希望小时位于垃圾箱的中心,而不是边缘。

我提到了this question / answer,但它似乎也没有回答这个问题。

我为直方图尝试了以下代码,但它没有为值 23 绘制条形

plt.hist(hour_list, bins=np.arange(24)-0.5)

谁能帮我弄到 24 个箱子,每个箱子都以小时为中心?

【问题讨论】:

    标签: python matplotlib histogram


    【解决方案1】:

    要获得 24 个 bin,您需要在序列中定义 bin 边缘的 25 个值。 n bins 总是有 n+1 边。

    所以,改变你的路线

    plt.hist(hour_list,bins=np.arange(24)-0.5)
    

    plt.hist(hour_list,bins=np.arange(25)-0.5)
    

    注意 - 您的测试数据应该包含两个边缘情况。如果您只是通过四舍五入提取小时数,列表中应该有一些 0 值。


    完整示例:

    import matplotlib.pyplot as plt
    import numpy as np
    
    def plot_my_time_based_histogram():
        #Note - changed the 24 values for 0
        time_new=[9, 23, 19, 9, 1, 2, 19, 5, 4, 20, 23, 10, 20, 5, 21, 17, 4, 13, 8, 13, 6, 19, 9, 14, 9, 10, 23, 19, 23, 20, 19, 6, 5, 0, 20, 19, 15, 14, 19, 14, 15, 21]
        fig, ax = plt.subplots()
        hour_list = time_new
        print hour_list
        numbers=[x for x in xrange(0,24)]
        labels=map(lambda x: str(x), numbers)
        plt.xticks(numbers, labels)
        #Make limit slightly lower to accommodate width of 0:00 bar
        plt.xlim(-0.5,24)
        plt.hist(hour_list,bins=np.arange(25)-0.5)
    
        # Further to comments, OP wants arbitrary labels too.
        labels=[str(t)+':00' for t in range(24)]
        ax.set_xticklabels(labels)
        plt.show()
    
    plot_my_time_based_histogram()
    

    结果:

    【讨论】:

    • 一个额外的问题,只是为了使解决方案普遍适用。几个月来我一直在尝试做类似的事情。因此,我希望 x 轴由字符串而不是数字组成。会计。到你的解决方案plt.hist(hour_list,bins=np.arange(13) - 0.5) 我会得到居中的号码。但是如何将 ['Jan', 'Feb'...] 这样的字符串居中。
    • @AbhishekBhatia 您可以更改 xticklabels 以将数字更改为字符串
    • @JRichardSnape 您能否提供解决方案中的示例。我试过plt.xticks(np.arange(13) - 0.5,label) plt.hist(hour_list,bins=np.arange(13) - 0.5),但它不正确('居中')。
    • 我没有得到你想要的。如果您有 24 个值并且您有 12 个 bin,则它们每个将包含 2 个值。为什么从 25 换到 13?我们为什么要引入几个月?您在这里缺少该站点的模型 - 我们不能只是在 cmets 中添加越来越多的问题。正如@tom 所说-如果您想要任意标签文本,请更改xticklabels。你可以谷歌“matplotlib set xtick labels”,你会得到stackoverflow.com/questions/11244514/…作为第一个结果,这解释了它
    • @AbhishekBhatia 您的标签数量是否与垃圾箱数量相匹配?我敢打赌,你有 24 个垃圾箱的 25 个标签......如果你需要 0 在第一个垃圾箱的中心,你可能需要 0 在最后一个垃圾箱的中心 24。请注意,您有 25 个垃圾箱,而您的 024 垃圾箱是不明确的 - 恰好在午夜发生的事件进入哪个垃圾箱?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 2016-07-07
    • 2017-02-18
    • 1970-01-01
    • 2019-12-08
    相关资源
    最近更新 更多