Search code examples
pandaslegend-properties

Pandas secondary_y: How to place legends outside plot?


I am struggling moving the location of legends when I use "secondary_y" in Pandas. The below code gives an example:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'C' : [4,5,6,7], 'S' : [10,20,30,40],'R' : [100,50,-30,-50]})
fig, ax = plt.subplots()
df[['C', 'S', 'R']].plot.bar(ax=ax, rot=90,  secondary_y= ['S', 'R'])

enter image description here

When not using "secondary_y" the following works

handles, labels = ax.get_legend_handles_labels()
fig.legend(handles, labels, loc='lower left', ncol=3,
           bbox_to_anchor=(0.25, -.175))

But the last code above does not work when I use "secondary_y".

Does anybody know how to get the legend below the figure?


Solution

  • The following, which I found at https://stackoverflow.com/a/54091202/8046133, worked

    h1, l1 = ax.get_legend_handles_labels()
    h2, l2 = ax.right_ax.get_legend_handles_labels()
    handles = h1+h2
    labels = l1+l2
    ax.legend(handles, labels, loc='lower left', ncol=3,
           bbox_to_anchor=(0.25, -.575))