2016-11-29 82 views
0

我试图做一些数据,我有出于某种原因,直方图保持显示0`th酒吧以及(这在我的情况下是空的)的直方图 这里我的代码Python的pyplot直方图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

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

所以总是最好考虑放在哪里并通过向bins提供数组手动设置它们。这个阵列被解释为二进制位的限制,因此,例如设定bins[6,8,11]产生两个箱,与所述第一范围从6到8(不包括8.00),并从8至11

第二In你的情况要12个箱,所以你需要1和13之间的数字13,以提供bins,使得价值1属于第一仓,从1到2,和12属于最后一箱从12到13

这已经交出了漂亮的直方图,但因为你只有整数,分箱宽度是一种违反直觉。因此不是在bin中间为中心的酒吧,你可能想在左边点,可以通过align="left"做才能居中。

在最后你可以设置就像你喜欢的情节的限制。

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

enter image description here

+0

谢谢,这很有道理。 – Saik

1

如何尝试以下?

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

对于微调,你可以随时更改参数bins,但对于轴系可以通过axis改变。

+0

设置仓为'A = np.array(列表(范围(1,13)))'的问题(心中有一托架缺失)是,它会产生' 11个垃圾箱。然而提问者想要12个垃圾箱。 – ImportanceOfBeingErnest

+0

谢谢,重要!我纠正了它。 –