pandas 如何使用每个离散值创建条形图/直方图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/18393887/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a bar chart/histogram with bar per discrete value?
提问by d1337
I am trying to create a histogram that will show the amount of ratings per value in a discrete star ratings (1-5). There should be a bar per value, and in the x-axis the only numbers to be shown are [1,2,3,4,5] underneath each bar (centered).
我正在尝试创建一个直方图,它将显示离散星级评分 (1-5) 中每个值的评分数量。每个值应该有一个条形,在 x 轴上,唯一显示的数字是每个条形下方的 [1,2,3,4,5](居中)。
I tried setting the amount of bins to 5 or their range to be from 0-7, but that creates bars that span across values (as in the image supplied)
我尝试将 bin 的数量设置为 5 或将它们的范围设置为 0-7,但这会创建跨越值的条(如提供的图像所示)


This is the code I have tried (pandas and numpy):
这是我尝试过的代码(pandas 和 numpy):
df.stars.hist()
and
和
hist, bins = np.histogram(x1, bins=5)
ax.bar(bins[:-1], hist.astype(np.float32) / hist.sum(), width=(bins[1]-bins[0]), color="blue")
回答by Phillip Cloud
You can use the plot(kind='bar')method:
您可以使用以下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()
to get:
要得到:


EDIT #1:To show them as proportions just divide by the sum
编辑 #1:要将它们显示为比例,只需除以sum
vc /= float(vc.sum())
assert vc.sum() == 1
to get:
要得到:


EDIT #2:To show them as percentages divide by the sum as above and use the format spec mini-language to format the y-axis tick labels
编辑#2:将它们显示为百分比除以上述总和,并使用格式规范迷你语言来格式化 y 轴刻度标签
new_labels = ['{0:.0%}'.format(float(x.get_text())) for x in ax.get_yticklabels()]
ax.set_yticklabels(new_labels)
to get:
要得到:



