Setting a relative frequency in a matplotlib histo

2019-01-22 07:51发布

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.

Here is the code:

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

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!

2条回答
Explosion°爆炸
2楼-- · 2019-01-22 08:23

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

What you need is something like that:

 # assuming that mydata is an numpy array
 ax.hist(mydata, weights=np.zeros_like(data) + 1. / data.size)
 # this will give you fractions
查看更多
地球回转人心会变
3楼-- · 2019-01-22 08:25

Or you can use set_major_formatter to adjust the scale of the y-axis, as follows:

from matplotlib import ticker as tick

def adjust_y_axis(x, pos):
    return x / (len(mydata) * 1.0)

ax.yaxis.set_major_formatter(tick.FuncFormatter(adjust_y_axis))

just call adjust_y_axis as above before plt.show().

查看更多
登录 后发表回答