Python:访问具有两个y轴的图表图例

Python:访问具有两个y轴的图表图例,python,pandas,matplotlib,graph,Python,Pandas,Matplotlib,Graph,使用Pandasplot功能,创建具有辅助y轴的图表非常简单。但是,例如,我如何访问图例以更改字体大小、删除边框或更改其位置 我尝试使用axis.get\u legend\u handles\u labels()函数。但这并不像预期的那样有效 df = pd.DataFrame(np.random.randint(0, 100, (20, 2)), index=pd.date_range('20190101', periods=20),

使用Pandas
plot
功能,创建具有辅助y轴的图表非常简单。但是,例如,我如何访问图例以更改字体大小、删除边框或更改其位置

我尝试使用
axis.get\u legend\u handles\u labels()
函数。但这并不像预期的那样有效

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()

dataframe
plot
功能返回轴

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

dataframe
plot
功能返回轴

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

可以通过访问轴对象中的控制柄和标签来创建合并图例。这是一个由解决方案驱动的答案。现在您可以指定位置、fontsize、
frameon

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)

通过从轴对象访问控制柄和标签,可以创建合并图例。这是一个由解决方案驱动的答案。现在您可以指定位置、fontsize、
frameon

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)