Python Can';t使用bbox_将图例位置更改为_锚定

Python Can';t使用bbox_将图例位置更改为_锚定,python,pandas,matplotlib,plot,legend,Python,Pandas,Matplotlib,Plot,Legend,我从数据框中绘制数据,其中一部分进入主y轴,另一部分进入次y轴。我分两步绘制,如下所示: ax=data[['Energy (kWh)','Reactive Energy( kVArh)','CFE',"CFE'"]].plot(figsize=(12,8),xlim=('2020-08-01','2020-08-02'),title='Energy Plots vs. Time',grid=True) ax2=data[['PF no Cap','Power Factor

我从数据框中绘制数据,其中一部分进入主y轴,另一部分进入次y轴。我分两步绘制,如下所示:

ax=data[['Energy (kWh)','Reactive Energy( kVArh)','CFE',"CFE'"]].plot(figsize=(12,8),xlim=('2020-08-01','2020-08-02'),title='Energy Plots vs. Time',grid=True)
ax2=data[['PF no Cap','Power Factor CRE CdR']].plot(secondary_y=True,ax=ax)
我有绘图,轴标签和所有我需要的东西,但是图例放错地方了。我希望它在绘图之外,但当我使用bbox__锚定时,会创建第二个图例,并且它只有与ax2关联的标签(PF无上限,功率因数CRE CdR)

如何将带有所有标签的图例移动到绘图外部

在这里,我放置了整个代码和一些说明问题的图片:

data["CFE'"]=(data['Reactive Energy( kVArh)']-Qcap).clip_lower(0)
data['CFE']=(data['Reactive Energy( kVArh)']-Qcap)
data['PF no Cap']=np.cos(np.arctan(data['Reactive Energy( kVArh)']/data['Energy (kWh)']))
data['Power Factor CRE CdR']=np.cos(np.arctan((data['Reactive Energy( kVArh)']-Qcap_mod).clip_lower(0)/data['Energy (kWh)']))


ax=data[['Energy (kWh)','Reactive Energy( kVArh)','CFE',"CFE'"]].plot(figsize=(12,8),xlim=('2020-08-01','2020-08-02'),title='Energy Plots vs. Time',grid=True)
ax2=data[['PF no Cap','Power Factor CRE CdR']].plot(secondary_y=True,ax=ax)

ax.set(xlabel='Date',ylabel='Energy')
plt.legend(bbox_to_anchor=(1.3,0.7))
这将生成以下曲线图:


事先谢谢

函数的
plt.XXXX
系列仅作用于当前轴,在本例中是
ax2
,因为它是最后创建的。我最初认为调用
ax.legend(…)
就可以了,但这也不起作用,因为它只考虑来自该轴的艺术家,而不考虑来自ax2的艺术家

最简单的解决方案不是重新创建图例,而是使用
ax.legend.set\u bbox\u to_anchor(…)

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()

ax=df[['A','B']].plot(title='Energy Plots vs. Time',grid=True)
ax2=df[['C','D']].plot(secondary_y=True,ax=ax)

ax.set(xlabel='Date',ylabel='Energy')
ax.legend_.set_bbox_to_anchor((1.3,0.7))
plt.tight_layout()