2

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: enter image description here

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

1
  • Have you tried reading out the axis limits and calculating the relative location yourself? Commented Dec 14, 2019 at 9:03

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.