How to add a shared x-label and y-label to a plot created with Pandas' plot? (Matplotlib)

When creating multiple subplots with Pandas' plot() method, you can add shared x-labels and y-labels using the sharex=True and sharey=True parameters. This is particularly useful for comparing related data across multiple charts.

Basic Shared Axes Example

Here's how to create subplots with shared axes using Pandas DataFrames ?

import pandas as pd
import matplotlib.pyplot as plt

# Set figure size for better visualization
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

# Create sample data
df = pd.DataFrame(
    {'First': [0.3, 0.2, 0.5, 0.2], 
     'Second': [0.1, 0.0, 0.3, 0.1],
     'Third': [0.2, 0.5, 0.0, 0.7], 
     'Fourth': [0.6, 0.3, 0.4, 0.6]},
    index=['Q1', 'Q2', 'Q3', 'Q4'])

# Create subplots with shared axes
axes = df.plot(kind="bar", subplots=True, layout=(2, 2),
               sharey=True, sharex=True, 
               title="Quarterly Performance by Category")

plt.show()

Adding Custom Labels to Shared Axes

You can add custom shared labels using matplotlib's suptitle() and figure text methods ?

import pandas as pd
import matplotlib.pyplot as plt

# Create sample data
df = pd.DataFrame(
    {'Sales': [100, 120, 110, 130], 
     'Marketing': [50, 60, 55, 65],
     'Operations': [80, 85, 75, 90]},
    index=['Jan', 'Feb', 'Mar', 'Apr'])

# Create figure and subplots
fig, axes = plt.subplots(2, 2, figsize=(10, 8), sharex=True, sharey=True)
fig.suptitle('Department Performance Analysis', fontsize=16)

# Plot each column in a separate subplot
for i, col in enumerate(df.columns):
    row, col_idx = divmod(i, 2)
    df[col].plot(kind='bar', ax=axes[row, col_idx], title=col, color='skyblue')

# Remove the empty subplot
axes[1, 1].remove()

# Add shared labels
fig.text(0.5, 0.02, 'Months', ha='center', fontsize=12)
fig.text(0.02, 0.5, 'Values', va='center', rotation='vertical', fontsize=12)

plt.tight_layout()
plt.show()

Parameters Explanation

Parameter Description Effect
sharex=True Share x-axis across subplots Same x-axis scale and labels
sharey=True Share y-axis across subplots Same y-axis scale and labels
layout=(2,2) Subplot arrangement 2 rows, 2 columns grid
subplots=True Create separate subplot for each column Multiple charts in one figure

Key Benefits

  • Space Efficiency − Reduces redundant axis labels
  • Easy Comparison − Same scales make data comparison straightforward
  • Clean Layout − Professional-looking multi-panel plots
  • Automatic Scaling − Pandas handles axis scaling automatically

Conclusion

Use sharex=True and sharey=True in Pandas' plot() method to create subplots with shared axes. This creates cleaner visualizations and makes data comparison easier across multiple charts.

---
Updated on: 2026-03-25T23:05:21+05:30

896 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements