user667489
user667489

Reputation: 9569

Matplotlib set legend labels for double axis plot

I have produced a bar + lines plot using the following sort of code:

import pandas as pd
import matplotlib
import numpy as np
import random
%matplotlib inline

df = pd.DataFrame(np.random.randint(0,100,size=(20, 5)), columns=list('ABCDE'))


ax = df[['E']].plot(
    secondary_y = True,
    x=df.A,
    kind='bar',

)

ax.legend(['EE'])

df[['A','B','C','D']].plot(
    linestyle='-',
    marker='o',
    ax=ax    
)
ax.legend(['AA','BB','CC','DD'])
ax.autoscale(enable=True, axis='both', tight=False)

I would like to change the legend entries for each of the series on the plot (e.g. to AA instead of A and so on), but I'm struggling to work out how to do this. Can anyone help?

I tried running ImportanceOfBeingErnest's code using matplotlib 2.0.2 and got the following error, but after upgrading to 2.1 it works.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-c26e970bbe42> in <module>()
     10 
     11 ax.figure.legend(['AA','BB','CC','DD'], 
---> 12                  bbox_to_anchor=(1.,1),loc=1, bbox_transform=ax.transAxes)
     13 ax.autoscale(enable=True, axis='both', tight=False)
     14 plt.show()

TypeError: legend() missing 1 required positional argument: 'labels'

Upvotes: 0

Views: 6612

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339102

The following works with matplotlib 2.1 or higher.

You could add a figure legend, which will take into account all the artists from all figures. Then setting legend=False to the individual pandas plots, and creating one legend in the end would probably give you what you want.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline

df = pd.DataFrame(np.random.randint(0,100,size=(20, 5)), columns=list('ABCDE'))

ax = df[['E']].plot( secondary_y = True,  x=df.A, kind='bar', legend=False)
ax = df[['A','B','C','D']].plot(  linestyle='-', marker='o',legend=False, ax=ax)

ax.figure.legend(['AA','BB','CC','DD'], 
                 bbox_to_anchor=(1.,1),loc=1, bbox_transform=ax.transAxes)
ax.autoscale(enable=True, axis='both', tight=False)
plt.show()

enter image description here

Upvotes: 1

Related Questions