Andi
Andi

Reputation: 4855

Python: Access the legend of a chart with two y-axis

Using the Pandas plot function, it is quite simple to create a chart with a secondary y-axis. But how can I access the legend in order to change the font size or get rid of the frame or change its location, for example?

I tried to make use of the axis.get_legend_handles_labels() function. But this is not working as expected.

df = pd.DataFrame(np.random.randint(0, 100, (20, 2)),
                  index=pd.date_range('20190101', periods=20),
                  columns=list('AB'))

df.plot(secondary_y=['B'])

ax = plt.gca()
handles, labels = ax.get_legend_handles_labels()

Upvotes: 0

Views: 86

Answers (2)

Sheldore
Sheldore

Reputation: 39042

You can create the merged legend by accessing the handles and the labels from the axis objects. Here is an answer motivated by this solution. Now you can specify the location, fontsize, frameon, etc.

np.random.seed(981)

df = pd.DataFrame(np.random.randint(0, 100, (20, 2)),
                  index=pd.date_range('20190101', periods=20),
                  columns=list('AB'))

ax = df.plot(secondary_y=['B'])

lines = ax.get_lines() + ax.right_ax.get_lines()

ax.legend(lines, [l.get_label() for l in lines], 
          loc='upper left', frameon=False, fontsize=20)

enter image description here

Upvotes: 2

abhilb
abhilb

Reputation: 5757

The plot function of pandas dataframe returns the axes.

ax = df.plot(secondary_y=['B'])
h,l = ax.get_legend_handles_labels()

Upvotes: 0

Related Questions