Secondary axis with twinx(): how to add to legend
Here goes the turbo version: To combine primary and secondary axes legends in Matplotlib with twinx()
, simply collect the legends from each and merge them. Here's the code to do that:
This ensures both axes are represented in your legend, giving a proper narrative to your plot.
Level-up your legend game
Well, we've got the basics covered. Ready to turn this from a basic grocery list...into a Michelin-star menu?
Controlling legend location
Move around the legend like you do in your own house. The location is totally up to you!
Just pick a location key or use an (x, y)
tuple, and your legend will find its way there.
Giving legends a makeover
If there was a Project Runway
for legends, you'd want to work on those colors and fonts:
Spruce up your legends with frameon
, title
, and play around with fontsize
and title_fontsize
.
Inviting error bars to the legend party
Plot error bars like a boss and include them in your legend — because everybody loves a humblebrag:
This subtly tells whoever's looking at your plot that your data is honest and modest.
Whoa, wait. There's auto-labeling?
Reduce congestion in your code by assigning labels as you plot. It's like traffic control for your code:
Matplotlib will do the heavy lifting and automatically generate the legend entries.
Say it with markers
Markers are like spices. They add flavor to your data. And who doesn't like flavor?
These provide an extra layer of distinction on top of colors.
Keeping clarity on the twin axes
The power of 'twinx()' comes with a price — possible confusion. Avoid it by making a clear distinction between the primary and secondary axes:
Was this article helpful?