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
Selected Reading
How to add legends and title to grouped histograms generated by Pandas? (Matplotlib)
To add legends and title to grouped histograms generated by Pandas, we can use the DataFrame's plot() method with kind='hist' and then customize the plot using Matplotlib functions.
Basic Grouped Histogram with Title
First, let's create a DataFrame and plot a basic grouped histogram with a title ?
import matplotlib.pyplot as plt
import pandas as pd
# Set figure size for better visibility
plt.rcParams["figure.figsize"] = [10, 6]
# Create sample data
df = pd.DataFrame({
'Math': [85, 92, 78, 88, 95, 82, 90],
'Science': [88, 85, 92, 91, 87, 89, 86],
'English': [92, 88, 85, 87, 91, 88, 92],
'History': [78, 85, 88, 82, 86, 90, 84]
})
# Create grouped histogram
ax = df.plot(kind='hist', alpha=0.7, bins=8)
plt.title("Student Scores Distribution by Subject")
plt.xlabel("Score")
plt.ylabel("Frequency")
plt.show()
Customizing Legend Position
You can control the legend position and appearance for better readability ?
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams["figure.figsize"] = [10, 6]
df = pd.DataFrame({
'Math': [85, 92, 78, 88, 95, 82, 90],
'Science': [88, 85, 92, 91, 87, 89, 86],
'English': [92, 88, 85, 87, 91, 88, 92],
'History': [78, 85, 88, 82, 86, 90, 84]
})
# Create histogram with custom legend
ax = df.plot(kind='hist', alpha=0.7, bins=8)
plt.title("Student Scores Distribution by Subject", fontsize=16, fontweight='bold')
plt.xlabel("Score", fontsize=12)
plt.ylabel("Frequency", fontsize=12)
# Customize legend
plt.legend(title="Subjects", loc='upper right', fontsize=10)
plt.tight_layout()
plt.show()
Advanced Customization
For more control, you can customize colors, add grid, and modify legend properties ?
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
plt.rcParams["figure.figsize"] = [12, 7]
# Create more realistic sample data
np.random.seed(42)
df = pd.DataFrame({
'Quarter 1': np.random.normal(75, 10, 50),
'Quarter 2': np.random.normal(80, 8, 50),
'Quarter 3': np.random.normal(78, 12, 50),
'Quarter 4': np.random.normal(85, 9, 50)
})
# Create histogram with custom styling
ax = df.plot(kind='hist', alpha=0.8, bins=15,
color=['skyblue', 'lightgreen', 'coral', 'gold'])
# Add title and labels
plt.title("Sales Performance Distribution by Quarter",
fontsize=18, fontweight='bold', pad=20)
plt.xlabel("Sales Value ($)", fontsize=14)
plt.ylabel("Frequency", fontsize=14)
# Customize legend
plt.legend(title="Sales Quarters", loc='upper left',
fontsize=12, title_fontsize=13, frameon=True, shadow=True)
# Add grid for better readability
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Purpose | Example |
|---|---|---|
kind='hist' |
Specifies histogram plot | df.plot(kind='hist') |
alpha |
Controls transparency | alpha=0.7 |
bins |
Number of histogram bins | bins=15 |
plt.legend() |
Customizes legend appearance | plt.legend(loc='upper right') |
plt.title() |
Adds plot title | plt.title("My Plot") |
Conclusion
Use DataFrame's plot(kind='hist') to create grouped histograms, then add titles with plt.title() and customize legends with plt.legend(). The alpha parameter helps with overlapping bars visibility.
Advertisements
