Matplotlib为双轴图设置图例标签

时间:2018-01-23 12:40:20

标签: python matplotlib

我使用以下代码生成了一个条形+线条图:

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)

我想更改剧情中每个系列的图例条目(例如改为AA而不是A等等),但我很难弄清楚如何做这个。有人可以帮忙吗?

我尝试使用matplotlib 2.0.2运行ImportanceOfBeingErnest的代码并得到以下错误,但升级到2.1后它可以正常工作。

---------------------------------------------------------------------------
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'

1 个答案:

答案 0 :(得分:1)

以下适用于matplotlib 2.1或更高版本。

你可以添加一个图形图例,它将考虑所有图形中的所有艺术家。然后将legend=False设置为各个pandas图,最后创建一个图例可能会给你你想要的东西。

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

相关问题