pythonmatplotlib

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


Solution

  • 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