Explain Codes LogoExplain Codes Logo

Adding a y-axis label to secondary y-axis in matplotlib

python
matplotlib
dataframe
plotting
Nikita BarsukovbyNikita Barsukov·Jan 28, 2025
TLDR

Adding a label to secondary y-axis in Matplotlib is a piece of cake. You use set_ylabel() function on the secondary axis object (ax2 in this case) like below:

import matplotlib.pyplot as plt fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax2.set_ylabel('Secondary Label') plt.show()

Address the secondary axis (ax2) right after creation with twinx(). You can change label font and color attributes in your style.

Working with Dual Axes

To make sense of complex datasets, it is often necessary to work with dual axes. Here is how you add and manage a secondary y-axis in matplotlib.

Create a Secondary Y-axis

You create the secondary y-axis using the twinx() method. Then, attach a label to it using the set_ylabel() function:

import numpy as np import matplotlib.pyplot as plt # Sample data: x = np.linspace(0, 10, 100) y1 = np.exp(x) # Crazy exponential stuff y2 = np.log(x + 1) # Logarithmic "slowpoke" growth fig, ax1 = plt.subplots() # Primary y-axis and its talkative label ax1.plot(x, y1, 'g-') ax1.set_ylabel('Exponential Growth', color='g') # Secondary y-axis and its secretive label ax2 = ax1.twinx() ax2.plot(x, y2, 'b-') ax2.set_ylabel('Logarithmic Growth', color='b') # Shh, we're plotting! plt.show()

Style the Axes Labels

Remember, it's not just about the numbers. How you present the data matters too! Let's make the axes labels match their line color and set the font size to 14 for easier reading:

ax1.set_ylabel('Exponential Growth', color='g', fontsize=14) ax2.set_ylabel('Logarithmic Growth', color='b', fontsize=14)

Maintain Consistency between Axes

If your axes can't agree, who can? Let's introduce some diplomacy by mirroring the properties like limits and scales:

ax1.set_ylim(0, 10000) ax2.set_ylim(0, 10)

A Taste of Pandas

We do hear whispers of Pandas around here. For those plotting with Panda's sleek Matplotlib integration, use secondary_y=True to create an secondary axis, and label it using the right_ax.set_ylabel() method:

import pandas as pd # Let's say `df` is a pandas DataFrame with 'A' and 'B' columns ax = df['A'].plot() ax.set_ylabel('Primary Axis Label') ax2 = df['B'].plot(secondary_y=True) ax2.right_ax.set_ylabel('Secondary Axis Label')

The Finer Details: Customization

Feel free to let your imagination run wild (responsibly wild, we hope). You can customize the label to your heart's content:

ax2.set_ylabel('Money ($)', fontsize=12, color='darkgreen')

You might find it easier sometimes to work with the current active axis. In cases like that, use plt.gca().twinx():

ax2 = plt.gca().twinx()