Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set legend position when plotting a pandas dataframe with a second y-axis via pandas plotting interface [duplicate]

I am plotting a pandas dataframe with a second y-axis via pandas plotting interface as described in the documentation like this:

df = pd.DataFrame(np.random.randn(24*3, 3),
                  index=pd.date_range('1/1/2019', periods=24*3, freq='h'))
df.columns = ['A (left)', 'B (right)', 'C (right)']
ax = df.plot(secondary_y=['B (right)', 'C (right)'], mark_right=False)
ax.set_ylabel('A scale')
ax.right_ax.set_ylabel('BC scale')
ax.legend(loc='upper right')
plt.show()

which yields enter image description here As it can be seen, the legend looses entries when I set the position using ax.legend(loc='upper right').

Does anyone know how I can set the legend position and keep all entries?

Thanks in advance!

like image 517
Cord Kaldemeyer Avatar asked Oct 16 '25 15:10

Cord Kaldemeyer


1 Answers

We can use .get_legend_handles_labels() for a more correct solution:

np.random.seed(42)

df = pd.DataFrame(np.random.randn(24*3, 3),
                  index=pd.date_range('1/1/2019', periods=24*3, freq='h'))
df.columns = ['A (left)', 'B (right)', 'C (right)']
ax = df.plot(secondary_y=['B (right)', 'C (right)'], mark_right=False)
ax.set_ylabel('A scale')
ax.right_ax.set_ylabel('BC scale')

h1, l1 = ax.get_legend_handles_labels()
h2, l2 = ax.right_ax.get_legend_handles_labels()
ax.legend(h1+h2, l1+l2, loc=1)

enter image description here

The reason we need to use that method is because ax and ax.right_ax each have their own legend and simply setting them to the same location will render them on top of each other.

like image 166
Charles Landau Avatar answered Oct 18 '25 08:10

Charles Landau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!