显示Python pyplot直方图0条

2024-04-23 22:04:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着对我的一些数据做一个柱状图,由于某种原因,柱状图也一直显示第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]

请注意,日本地震包含1到12个数字。在

这是我得到的柱状图

enter image description here

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

为了解决这个问题,我试着做以下几点

^{pr2}$

但通过这样做,似乎最后2个小节堆积在一起,我最终得到了11个小节而不是12个小节。在

还有没有办法让x轴的数字出现在每个条下面?在


Tags: ofcsv数据密码numberread数字例子
2条回答

首先,在大多数情况下,如果没有进一步的说明,设置料仓的数量将失败。在这里,你对箱子做了一些隐含的假设,即你想要12个箱子,在1到13之间等距。(但纽比怎么知道?!)在

因此,最好考虑将存储箱放在何处,并通过向bins提供一个数组来手动设置它们。此数组被解释为存储单元的限制,因此例如,将bins设置为[6,8,11]将生成两个存储单元,第一个存储单元的范围为6到8(不包括8.00),第二个存储单元的范围为8到11。在

在您的例子中,您需要12个bin,因此需要提供1到13到bins之间的13个数字,这样值1属于第一个bin,范围从1到2,而{}属于从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

试试下面这些怎么样?在

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

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

相关问题 更多 >