Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib histogram: how to display the count over the bar?

With matplotlib's hist function, how can one make it display the count for each bin over the bar?

For example,

import matplotlib.pyplot as plt
data = [ ... ] # some data
plt.hist(data, bins=10)

How can we make the count in each bin display over its bar?

like image 787
xuhdev Avatar asked Oct 03 '16 23:10

xuhdev


People also ask

How do I display the count over the bar in MatPlotLib histogram?

To display the count over the bar in matplotlib histogram, we can iterate each patch and use text() method to place the values over the patches.

How do you show the count in bar chart in Python?

Use the syntax “for index, value in enumerate(iterable)” with iterable as the list of bar values to access each index, value pair in iterable. At each iteration, call matplotlib. pyplot. text(x, y, s) with x as value, y as index, and s as str(value) to label each bar with its size.

How do you find a count on a histogram?

We can extract Frequency Counts of Histogram using hist() Function in R programming language. hist() function is used to plot a histogram out of the given data.


2 Answers

it seems hist can't do this,you can write some like :

your_bins=20
data=[]
arr=plt.hist(data,bins=your_bins)
for i in range(your_bins):
    plt.text(arr[1][i],arr[0][i],str(arr[0][i]))
like image 194
kiviak Avatar answered Sep 29 '22 04:09

kiviak


Not solution solely using plt.hist() but with some added functionality.

If you don't want to specify your bins beforehand and only plot densities bars, but also want to display the bin counts you can use the following.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randn(100)
density, bins, _ = plt.hist(data, density=True, bins=20)
count, _ = np.histogram(data, bins)
for x,y,num in zip(bins, density, count):
    if num != 0:
        plt.text(x, y+0.05, num, fontsize=10, rotation=-90) # x,y,str

The result looks as follows:

enter image description here

like image 24
v.tralala Avatar answered Sep 29 '22 04:09

v.tralala