Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to write text above the bars on a bar plot (Python Matplotlib)?
Adding text labels above bars in a matplotlib bar plot helps display exact values for better data interpretation. We can achieve this using the text() method to position labels at the top of each bar.
Basic Setup
First, let's create a simple bar plot with population data across different years ?
import matplotlib.pyplot as plt
import numpy as np
# Sample data
years = [1901, 1911, 1921, 1931, 1941, 1951, 1961, 1971, 1981, 1991, 2001, 2011]
population = [237.4, 238.4, 252.09, 251.31, 278.98, 318.66, 361.09,
439.23, 548.16, 683.33, 846.42, 1028.74]
# Create the bar plot
fig, ax = plt.subplots(figsize=(12, 6))
bars = ax.bar(years, population, width=8, color='skyblue', alpha=0.7)
# Basic formatting
ax.set_ylabel('Population (in millions)')
ax.set_title('Population Growth Over Years')
ax.set_xlabel('Year')
plt.show()
Adding Text Above Bars
Now let's add text labels showing the exact population values above each bar ?
import matplotlib.pyplot as plt
import numpy as np
years = [1901, 1911, 1921, 1931, 1941, 1951, 1961, 1971, 1981, 1991, 2001, 2011]
population = [237.4, 238.4, 252.09, 251.31, 278.98, 318.66, 361.09,
439.23, 548.16, 683.33, 846.42, 1028.74]
fig, ax = plt.subplots(figsize=(12, 6))
bars = ax.bar(years, population, width=8, color='skyblue', alpha=0.7)
# Add text above each bar
for bar in bars:
height = bar.get_height()
ax.text(x=bar.get_x() + bar.get_width() / 2,
y=height + 10,
s=f'{height}',
ha='center', va='bottom',
fontsize=9)
ax.set_ylabel('Population (in millions)')
ax.set_title('Population Growth Over Years with Value Labels')
ax.set_xlabel('Year')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Method Using Enumerate
An alternative approach using enumerate() for positioning text labels ?
import matplotlib.pyplot as plt
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]
fig, ax = plt.subplots(figsize=(8, 6))
bars = ax.bar(categories, values, color=['red', 'green', 'blue', 'orange', 'purple'])
# Add text using enumerate
for i, (category, value) in enumerate(zip(categories, values)):
ax.text(i, value + 1, str(value), ha='center', va='bottom', fontweight='bold')
ax.set_ylabel('Values')
ax.set_title('Bar Chart with Text Labels')
plt.show()
Customizing Text Appearance
You can customize the text appearance with different fonts, colors, and positioning ?
import matplotlib.pyplot as plt
products = ['Product A', 'Product B', 'Product C', 'Product D']
sales = [150, 280, 190, 340]
fig, ax = plt.subplots(figsize=(10, 6))
bars = ax.bar(products, sales, color='lightcoral', edgecolor='black', linewidth=1.2)
# Customized text labels
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2., height + 5,
f'${height}K',
ha='center', va='bottom',
fontsize=12, fontweight='bold',
color='darkred')
ax.set_ylabel('Sales (in thousands)')
ax.set_title('Product Sales with Custom Labels', fontsize=14, fontweight='bold')
ax.set_ylim(0, max(sales) + 50)
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Common Values |
|---|---|---|
ha |
Horizontal alignment | 'center', 'left', 'right' |
va |
Vertical alignment | 'bottom', 'center', 'top' |
fontsize |
Text size | 8, 10, 12, 'small', 'large' |
fontweight |
Text weight | 'normal', 'bold' |
Conclusion
Use ax.text() with bar.get_height() to position labels above bars. The key is calculating the correct x-position using bar.get_x() + bar.get_width()/2 for center alignment. Customize appearance with font parameters for better visual appeal.
