Adding a y-axis label to secondary y-axis in matplotlib
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:
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:
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:
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:
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:
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:
You might find it easier sometimes to work with the current active axis. In cases like that, use plt.gca().twinx()
:
Was this article helpful?