在matplotlib直方图中设置相对频率 [英] Setting a relative frequency in a matplotlib histogram

查看:318
本文介绍了在matplotlib直方图中设置相对频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据作为浮点数列表,我想将其绘制为直方图. Hist()函数完美地完成了绘制绝对直方图的工作.但是,我无法弄清楚如何以相对频率格式表示它-我想将其表示为y轴上的分数或理想情况下用百分比表示.

I have data as a list of floats and I want to plot it as a histogram. Hist() function does the job perfectly for plotting the absolute histogram. However, I cannot figure out how to represent it in a relative frequency format - I would like to have it as a fraction or ideally as a percentage on the y-axis.

这是代码:

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(mydata, bins=100, normed=1, cumulative=0)
ax.set_xlabel('Bins', size=20)
ax.set_ylabel('Frequency', size=20)
ax.legend

plt.show()

我认为normed = 1参数可以做到这一点,但是它给出的分数太高,有时大于1.它们似乎也取决于bin的大小,好像它们没有通过bin大小或其他东西归一化一样.但是,当我将cumulative = 1设置为1时,它的总和很好.因此,捕获量在哪里?顺便说一句,当我将相同的数据输入到Origin并将其绘制时,它为我提供了完全正确的分数.谢谢!

I thought normed=1 argument would do it, but it gives fractions that are too high and sometimes are greater than 1. They also seem to depend on the bin size, as if they are not normalized by the bin size or something. Nevertheless, when I set cumulative=1, it nicely sums up to 1. So, where is the catch? By the way, when I feed the same data into Origin and plot it, it gives me perfectly correct fractions. Thank you!

推荐答案

因为hist的规范化选项会返回点的密度,例如dN/dx

Because normed option of hist returns the density of points, e.g dN/dx

您需要的是这样的

 # assuming that mydata is an numpy array
 ax.hist(mydata, weights=np.zeros_like(mydata) + 1. / mydata.size)
 # this will give you fractions

这篇关于在matplotlib直方图中设置相对频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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