如何创建每个离散值条形图的条形图/直方图?

时间:2013-08-23 02:50:17

标签: python matplotlib pandas

我正在尝试创建一个直方图,该直方图将显示离散星级(1-5)中每个值的评级数量。 每个值应该有一个条形,在x轴上,每个条形下面(中心)下显示的唯一数字是[1,2,3,4,5]。

我尝试将容器数量设置为5或其范围设置为0-7,但是会创建跨越值的条形图(如提供的图像中所示)

enter image description here

这是我尝试过的代码(pandas and numpy):

df.stars.hist()

hist, bins = np.histogram(x1, bins=5)
ax.bar(bins[:-1], hist.astype(np.float32) / hist.sum(), width=(bins[1]-bins[0]), color="blue")

1 个答案:

答案 0 :(得分:8)

您可以使用plot(kind='bar')方法:

stars = Series(randint(1, 6, size=100))
vc = stars.value_counts().sort_index()
ax = vc.plot(kind='bar')
fig = ax.get_figure()
fig.autofmt_xdate()

得到:

enter image description here

编辑#1:要将它们显示为比例,只需除以sum

vc /= float(vc.sum())
assert vc.sum() == 1

得到:

enter image description here

编辑#2:要将它们显示为百分比除以上述总和,并使用格式规范迷你语言格式化y轴刻度标签

new_labels = ['{0:.0%}'.format(float(x.get_text())) for x in ax.get_yticklabels()]
ax.set_yticklabels(new_labels)

得到:

enter image description here