1

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?

Community
  • 1
  • 1
KJA
  • 313
  • 3
  • 14
  • Does this answer your question? [How to put the legend out of the plot](https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot) – wwnde Apr 27 '20 at 07:33
  • No, but I found an answer at https://stackoverflow.com/a/54091202/8046133. – KJA Apr 27 '20 at 07:37

1 Answers1

1

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))
KJA
  • 313
  • 3
  • 14