Matplotlib - Twin Axes
Matplotlib - Twin Axes
Section titled “Matplotlib - Twin Axes”Sometimes it’s useful to display two different datasets on the same plot area, but where the datasets have significantly different scales or units. Plotting them directly on the same y-axis might make one dataset hard to read or interpret.
Matplotlib allows you to create twin axes, which are additional axes objects that share the same x-axis (twinx()) or y-axis (twiny()) as the original axes, but have their own independent y-axis or x-axis on the opposite side of the plot.
Using ax.twinx()
Section titled “Using ax.twinx()”This is the most common use case: creating a second y-axis on the right side of the plot that shares the x-axis with the original (left) y-axis.
ax2 = ax1.twinx() # ax1 is the original Axes objectax2 is a new Axes object. You can plot data using ax2.plot(), set its y-axis limits using ax2.set_ylim(), and label its y-axis using ax2.set_ylabel(). Importantly, ax2 shares the x-axis with ax1, so zooming or panning the x-axis affects both.
Example: Plotting temperature and precipitation on the same graph.
import matplotlib.pyplot as pltimport numpy as np
# Sample data: Monthly average temperature and precipitationmonths = np.arange(1, 13)temperature = np.array([0, 2, 5, 10, 15, 18, 20, 19, 15, 10, 5, 1]) # Celsiusprecipitation = np.array([70, 60, 50, 40, 30, 20, 15, 20, 35, 50, 65, 75]) # mm
fig, ax1 = plt.subplots(figsize=(10, 5))
# Plot Temperature on the primary y-axis (left)color1 = 'tab:red'ax1.set_xlabel('Month')ax1.set_ylabel('Temperature (°C)', color=color1)line1 = ax1.plot(months, temperature, color=color1, marker='o', label='Temperature')ax1.tick_params(axis='y', labelcolor=color1)ax1.set_xticks(months)ax1.grid(True, axis='x', linestyle=':', alpha=0.7)
# Create the twin Axes sharing the x-axisax2 = ax1.twinx()
# Plot Precipitation on the secondary y-axis (right)color2 = 'tab:blue'ax2.set_ylabel('Precipitation (mm)', color=color2) # we already handled the x-label with ax1line2 = ax2.bar(months, precipitation, color=color2, alpha=0.6, label='Precipitation') # Use bar chart for precipitationax2.tick_params(axis='y', labelcolor=color2)ax2.set_ylim(0, max(precipitation) * 1.2) # Adjust limit for bars
# --- Adding Legends ---# Combining legends from two axes can be tricky. One way:lines = [line1[0], line2] # Get the plot objectslabels = [l.get_label() for l in lines]ax1.legend(lines, labels, loc='upper center') # Add legend using ax1
fig.suptitle('Monthly Temperature and Precipitation')fig.tight_layout() # Adjust layoutplt.show()Using ax.twiny()
Section titled “Using ax.twiny()”Less common, ax.twiny() creates a second x-axis (usually at the top) that shares the y-axis with the original axes.
ax2 = ax1.twiny() # ax1 is the original Axes objectThis might be useful if you want to show the same y-data against two different x-scales or variables.
Twin axes are powerful for combining plots with different scales, but use them judiciously. Overplotting too much information or using scales that obscure relationships can make plots confusing rather than informative. Ensure clear labeling and consider using color to associate lines/bars with their respective axes.