本文介绍了将值放在柱状图的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code to plot a histogram. The values in time_new are the hours when something occurred.

    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()

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

This produces a histogram, but the bins are not aligned as I would like. I want the hour to be in the centre of the bin, not on the edge.

我提到了此问题/答案 ,但似乎也无法回答这个问题.

I referred to this question / answer, but it seems not to answer the question either.

我尝试将以下代码用于直方图,但是它没有为值23

I tried the following code for the histogram plot instead, but it didn't plot a bar for the value 23

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

有人能帮我得到24个垃圾箱,每个小时都放在中心吗?

Can anyone help me to get 24 bins, with the hour at the centre of each?

推荐答案

要获取24个bin,您需要在序列中定义25个值以定义bin边缘. n bin总是有n+1条边.

To get 24 bins, you need 25 values in your sequence defining bin edges. There are always n+1 edges for n bins.

因此,更改您的行

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

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

注意-测试数据中应同时包含两种情况.如果您只是通过四舍五入来提取小时数,则列表中应该有一些0值.

Note - your test data should have both edge cases in it. If you are simply extracting hours by rounding, there should be some 0 values in the list.

完整示例:

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()

结果:

这篇关于将值放在柱状图的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-21 13:01