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
Stuffing a Pandas DataFrame.plot into a Matplotlib subplot
When working with data visualization in Python, you often need to combine Pandas plotting capabilities with Matplotlib's subplot functionality. This allows you to create multiple related plots in a single figure for better comparison and analysis.
Basic Setup
First, let's create a simple example showing how to embed Pandas DataFrame plots into Matplotlib subplots ?
import pandas as pd
import matplotlib.pyplot as plt
# Create sample data
df = pd.DataFrame({
'name': ['Joe', 'James', 'Jack'],
'age': [23, 34, 26],
'salary': [50000, 75000, 60000]
})
# Create subplots
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6))
# Plot on first subplot
df.set_index('name')['age'].plot(kind='bar', ax=ax1, title='Age by Name')
# Plot on second subplot
df.set_index('name')['salary'].plot(kind='bar', ax=ax2, title='Salary by Name')
plt.tight_layout()
plt.show()
Key Parameters
The ax parameter in DataFrame.plot() is crucial for directing the plot to a specific subplot ?
import pandas as pd
import matplotlib.pyplot as plt
# Sample time series data
dates = pd.date_range('2023-01-01', periods=10)
df = pd.DataFrame({
'sales': [100, 120, 90, 110, 130, 95, 140, 105, 125, 115],
'profit': [20, 25, 15, 22, 28, 18, 30, 21, 26, 23]
}, index=dates)
# Create 2x2 subplot grid
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# Different plot types on different subplots
df['sales'].plot(ax=axes[0,0], title='Sales Line Plot')
df['sales'].plot(kind='bar', ax=axes[0,1], title='Sales Bar Plot')
df['profit'].plot(ax=axes[1,0], title='Profit Line Plot', color='green')
df.plot(ax=axes[1,1], title='Combined Plot')
plt.tight_layout()
plt.show()
Advanced Example with Styling
You can customize each subplot independently while maintaining consistent styling ?
import pandas as pd
import matplotlib.pyplot as plt
# Create sample data
data = {
'Q1': [100, 150, 200, 120],
'Q2': [110, 160, 210, 130],
'Q3': [120, 170, 220, 140],
'Q4': [130, 180, 230, 150]
}
df = pd.DataFrame(data, index=['Product A', 'Product B', 'Product C', 'Product D'])
# Create subplots with shared styling
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
fig.suptitle('Quarterly Sales Analysis', fontsize=16)
# Plot each quarter in separate subplot
quarters = ['Q1', 'Q2', 'Q3', 'Q4']
positions = [(0,0), (0,1), (1,0), (1,1)]
for quarter, pos in zip(quarters, positions):
df[quarter].plot(kind='bar', ax=axes[pos], title=f'{quarter} Sales',
color=['skyblue', 'lightcoral', 'lightgreen', 'orange'])
axes[pos].set_ylabel('Sales ($1000s)')
axes[pos].tick_params(axis='x', rotation=45)
plt.tight_layout()
plt.show()
Comparison of Approaches
| Method | Use Case | Advantage |
|---|---|---|
plt.subplots() |
Multiple related plots | Easy subplot management |
df.plot(ax=ax) |
Direct Pandas integration | Simple syntax |
plt.tight_layout() |
Automatic spacing | Prevents overlap |
Conclusion
Use the ax parameter in DataFrame.plot() to direct plots to specific Matplotlib subplots. This approach combines Pandas' convenient plotting with Matplotlib's flexible layout system for professional visualizations.
