如何使用每个离散值的条形图创建条形图/直方图? [英] How to create a bar chart/histogram with bar per discrete value?

查看:122
本文介绍了如何使用每个离散值的条形图创建条形图/直方图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个直方图,以显示离散值星级(1-5)中每个值的星级数量. 每个值应有一个条形图,并且在x轴上,每个条形图(中心)下方仅显示[1,2,3,4,5].

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

我尝试将垃圾箱的数量设置为5,或者将垃圾箱的范围设置为0-7,但这会创建跨数值的条形图(如提供的图像)

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)

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

This is the code I have tried (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")

推荐答案

您可以使用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()

获得:

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

EDIT #1: To show them as proportions just divide by the sum

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

获得:

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

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

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

获得:

这篇关于如何使用每个离散值的条形图创建条形图/直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆