将值放在箱的中心以进行直方图

Abh*_*tia 3 python matplotlib histogram

我有以下代码来绘制直方图.值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()
Run Code Online (Sandbox Code Playgroud)

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

带有默认箱的time_new直方图

我提到了这个问题/答案,但似乎也没有回答这个问题.

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

plt.hist(hour_list, bins=np.arange(24)-0.5)
Run Code Online (Sandbox Code Playgroud)

指定了bin范围的直方图

任何人都可以帮助我获得24个垃圾箱,每个小时位于每个垃圾箱的中心吗?

J R*_*ape 7

要获得24个箱,您需要在序列中定义25个值来定义箱边.箱子总是有n+1边缘n.

所以,改变你的路线

plt.hist(hour_list,bins=np.arange(24)-0.5)
Run Code Online (Sandbox Code Playgroud)

plt.hist(hour_list,bins=np.arange(25)-0.5)
Run Code Online (Sandbox Code Playgroud)

注意 - 您的测试数据应包含两个边缘情况.如果您只是通过舍入来提取小时数,则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()
Run Code Online (Sandbox Code Playgroud)

结果:

带有居中箱的直方图

  • @AbhishekBhatia你可以改变`xticklabels`来将数字改为字符串 (2认同)