Matplotlib is a powerful Python library for creating visualizations. While labeling the primary y-axis is straightforward, adding a label to a secondary y-axis requires a slightly different approach. This article will guide you through the process, covering the basics and advanced customization techniques.
Table of Contents
- Understanding Y-Axes in Matplotlib
- Adding a Secondary Y-Axis Label
- Customizing the Y-Axis Label
- Using Pandas DataFrames
- Conclusion
- FAQ
Understanding Y-Axes in Matplotlib
Matplotlib plots typically have a single y-axis representing the dependent variable. However, when comparing datasets with vastly different scales, using a primary and secondary y-axis enhances readability. Each axis can be independently customized with labels, ticks, and more.
Adding a Secondary Y-Axis Label
Matplotlib’s twinx()
function creates a secondary y-axis sharing the same x-axis. The label is then set using the set_ylabel()
method on this new axes object.
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 1, 3, 5]
y2 = [10, 20, 15, 25, 30]
# Create the figure and axes
fig, ax1 = plt.subplots()
# Plot the first dataset
ax1.plot(x, y1, color='blue', label='Dataset 1')
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y1-axis Label', color='blue')
ax1.tick_params('y', labelcolor='blue')
ax1.legend(loc='upper left')
# Create the secondary y-axis
ax2 = ax1.twinx()
# Plot the second dataset
ax2.plot(x, y2, color='red', label='Dataset 2')
ax2.set_ylabel('Y2-axis Label', color='red') # Label for secondary y-axis
ax2.tick_params('y', labelcolor='red')
ax2.legend(loc='upper right')
plt.title('Plot with Secondary Y-Axis')
plt.show()
Customizing the Y-Axis Label
You can customize the label’s appearance:
- Font size:
ax2.set_ylabel('Label', fontsize=14)
- Font family:
ax2.set_ylabel('Label', fontfamily='serif')
- Rotation:
ax2.set_ylabel('Label', rotation=270)
- LaTeX formatting:
ax2.set_ylabel(r'$Delta$Label')
Using Pandas DataFrames
With Pandas, the process is similar:
import pandas as pd
import matplotlib.pyplot as plt
data = {'x': [1, 2, 3, 4, 5], 'y1': [2, 4, 1, 3, 5], 'y2': [10, 20, 15, 25, 30]}
df = pd.DataFrame(data)
fig, ax1 = plt.subplots()
df.plot(x='x', y='y1', ax=ax1, color='blue', label='Dataset 1')
ax1.set_ylabel('Y1-axis Label', color='blue')
ax1.legend(loc='upper left')
ax2 = ax1.twinx()
df.plot(x='x', y='y2', ax=ax2, color='red', label='Dataset 2')
ax2.set_ylabel('Y2-axis Label', color='red')
ax2.legend(loc='upper right')
plt.show()
Conclusion
Adding and customizing secondary y-axis labels in Matplotlib enhances data visualization clarity. twinx()
and set_ylabel()
are your key tools for creating informative and visually appealing plots.
FAQ
- Q: Multiple secondary y-axes? A: Yes, but excessive axes can hinder readability.
- Q: Adjusting limits? A: Use
ax2.set_ylim(ymin, ymax)
. - Q: Different scales? A: Secondary y-axes are designed for this; Matplotlib handles the scaling.