The Wayback Machine - https://web.archive.org/web/20240118182636/https://www.geeksforgeeks.org/how-to-display-the-value-of-each-bar-in-a-bar-chart-using-matplotlib/
Open In App
Related Articles

How to display the value of each bar in a bar chart using Matplotlib?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, we are going to see how to display the value of each bar in a bar chart using Matplotlib. There are two different ways to display the values of each bar in a bar chart in matplotlib –

Example 1: Using matplotlib.axes.Axes.text() function:

This function is basically used to add some text to the location in the chart. This function return string, this is always used with the syntax “for index, value in enumerate(iterable)” with iterable as the list of bar values to access each index, value pair in iterable so at it can add the text at each bar.

Python3




import os
import numpy as np
import matplotlib.pyplot as plt
 
x = [0, 1, 2, 3, 4, 5, 6, 7]
y = [160, 167, 17, 130, 120, 40, 105, 70]
fig, ax = plt.subplots()
width = 0.75
ind = np.arange(len(y))
 
ax.barh(ind, y, width, color = "green")
 
for i, v in enumerate(y):
    ax.text(v + 3, i + .25, str(v),
            color = 'blue', fontweight = 'bold')
plt.show()


Output:

Example 2: Use matplotlib.pyplot.text() function:

Call matplotlib.pyplot.barh(x, height) with x as a list of bar names and height as a list of bar values to create a bar chart. 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.

Python3




import matplotlib.pyplot as plt
x = ["A", "B", "C", "D"]
y = [1, 2, 3, 4]
plt.barh(x, y)
 
for index, value in enumerate(y):
    plt.text(value, index,
             str(value))
 
plt.show()


Output:


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 14 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials