简体   繁体   中英

Plotting histogram with text using python

I am trying to plot a histogram in python, and add text on the right upper corner.

here I am creating and plotting the histogram:

sample = stats.poisson.rvs(loc = 0,mu = lamda, size = 10001)
plt.hist(sample)
pd.DataFrame(sample).hist(bins=58, 
                          figsize=(9,9),
                          edgecolor="k", linewidth=1)

Now, I am trying to plot the mean and median in the right upper corner:

plt.text(0.8, 0.9, s = 'mean = {0}'.format(round(np.mean(sample), 2)))
plt.text(0.8, 0.8, s = 'median = {0}'.format(np.median(sample)))

and here is the screenshot of the output: 在此处输入图片说明

As you can see, the x and y values of the text are coordinate values.

How can I pass relative x and y values (to place the text in the upper right corner)?

You need to specify which coordinate system you want to use, otherwise it will automatically use the data coordinate system. In your case you want to use ax.transax .

plt.text(0.8, 0.9, s = 'mean = {0}'.format(round(np.mean(sample), 2)),transform=ax.transAxes)
plt.text(0.8, 0.8, s = 'median = {0}'.format(np.median(sample)),transform=ax.transAxes)

I suggest you to read this

You can also find an example in the matplotlib text documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM