Python pyplot histogram 0 bar正在显示

时间:2016-11-29 03:52:14

标签: python matplotlib histogram

我正在尝试制作一些我拥有的数据的直方图,并且由于某种原因,直方图也会一直显示第0个条(在我的情况下,这是空的) 这是我的代码

number_of_bins = 12
japanQuakes = pd.read_csv('JapanQuakes.csv', header=None).as_matrix()[1:,1].astype(np.int)
japanQuakes_histogram = plt.hist(japanQuakes, number_of_bins)

japanQuakes_histogram[0]

请注意,japanQuakes包含1到12之间的数字。

这是我得到的直方图

enter image description here

所以我想找到一种方法,使条形图填满整个图形,x轴从1而不是0开始。

我尝试按以下方法解决问题

A = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
japanQuakes_histogram = plt.hist(japanQuakes, A)

但通过这样做,似乎最后2个柱子堆叠在一起,我最终得到11个柱子而不是12个。

还有办法让x轴编号出现在每个条形图下面吗?

2 个答案:

答案 0 :(得分:2)

首先,在大多数情况下,设置没有任何进一步规范的箱数将失败。在这里,你对这些箱子做了一些隐含的假设,即你想要有12个箱子,在1到13之间等间隔。(但是numpy应该怎么知道?!)

因此,最好考虑放置垃圾箱的位置,并通过向bins提供数组来手动设置垃圾箱。此数组被解释为容器的限制,因此例如将[6,8,11]设置为bins会产生两个容器,第一个容量从6到8(不包括8.00),第二个从8到11。

在您的情况下,您需要12个bin,因此您需要提供1到13之间的13个数字到1,这样值12属于第一个bin,范围从1到2 ,align="left"属于12到13之间的最后一个bin。

这已经产生了一个很好的直方图,但是因为你只有整数,所以bin宽度有点违反直觉。因此,您可能希望将条形图集中在左侧点,而不是将条形图放在框架的中间位置,这可以通过import numpy as np import matplotlib.pyplot as plt # japanQuakes is the array [ 1 2 3 4 5 6 7 8 9 10 11 12] japanQuakes = np.arange(1,13) # if we want n bins, we need n+1 values in the array, since those are the limits bins = np.arange(1,14) japanQuakes_histogram, cbins, patches = plt.hist(japanQuakes, bins=bins, align="left") # just to verify: print japanQuakes_histogram #[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] print cbins #[ 1 2 3 4 5 6 7 8 9 10 11 12 13] # indeed we have one value between 1 and 2, one value between 2 and 3 and so on # set xticks to match with the left bin limits plt.gca().set_xticks(bins[:-1]) # if you want some space around plt.gca().set_xlim([bins[0]-1,bins[-1]]) # or if you want it tight #plt.gca().set_xlim([bins[0]-0.5,bins[-1]-0.5]) plt.show() 完成。

最后,您可以根据需要设置绘图的限制。

SRV

enter image description here

答案 1 :(得分:1)

如何尝试以下操作?

plt.axis([1,12,0,3000])
A = np.arange(1,14)
japanQuakes_histogram = plt.hist(japanQuakes, A)

对于微调,您始终可以更改参数bins,但可以通过axis更改轴。