Matplotlib Histogram with numbers on the top

Tzung-Chien Hsieh
1 min readJun 21, 2021

--

In this article, I will show an example of using matplotlib to make a histogram with numbers on the top of each bar.

Initialize data and figure.

We first use NumPy to generate random numbers. Then we create a figure as usual by plt.subplot() and plot the histogram.

Add numbers on the top of the figure.

For the number we want to put on the top of each bar, we need to get the position of each bar. So we use the bins return from ax.hist() to get the position on the x-axis. The position of the y-axis is the count which we already have. In the end, we use ax.text() to add the number on the top of each bar. The offset on the x and y-axis could be adjusted according to the bin size.

By the example above, we will have a histogram like the one shown below.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Tzung-Chien Hsieh
Tzung-Chien Hsieh

Written by Tzung-Chien Hsieh

PhD in Computer Science, I will share what I learned in Programming, Machine Learning, and Rare Disorders.

No responses yet

Write a response