调整与一个Python绘图关联的多个图例的图例布局?

调整与一个Python绘图关联的多个图例的图例布局?,python,pandas,dataframe,matplotlib,legend,Python,Pandas,Dataframe,Matplotlib,Legend,我正在从带有3个y轴的数据帧创建Python绘图。对于每个y轴,我要绘制多个y值。y轴的所有数据集都是根据共享日期x轴绘制的 代码如下所示: df = pd.read_excel (r'test.xlsx', sheet_name='test', engine='openpyxl') fig, ax = plt.subplots() ax3 = ax.twinx() rspine = ax3.spines['right'] rspine.set_position(('axes', 1.15))

我正在从带有3个y轴的数据帧创建Python绘图。对于每个y轴,我要绘制多个y值。y轴的所有数据集都是根据共享日期x轴绘制的

代码如下所示:

df = pd.read_excel (r'test.xlsx', sheet_name='test', engine='openpyxl')
fig, ax = plt.subplots()

ax3 = ax.twinx()
rspine = ax3.spines['right']
rspine.set_position(('axes', 1.15))
ax3.set_frame_on(True)
ax3.patch.set_visible(False)
fig.subplots_adjust(right=0.7)

ax.plot(df['Date'], df['Gas1'], label="Gas1", color='g')
ax.plot(df['Date'], df['Gas2'], label="Gas2", color='b')
ax.plot(df['Date'], df['Gas3'], label="Gas3", marker="o", markersize=2, color='r')
ax.set_xlabel("Date")
ax.set_ylabel("Gas Rate")

ax2 = ax.twinx()
ax2.plot(df['Date'], df['Water1'], label="Water1", color='k')
ax2.plot(df['Date'], df['Water2'], label="Water2", color='y')
ax2.set_ylabel("Water")

ax3.plot(df['Date'], df['Pressure1'], label="Pressure1")
ax3.plot(df['Date'], df['Pressure2'], label="Pressure2")
ax3.set_ylabel("Pressure")

ax.legend()
ax2.legend()
ax3.legend()
plt.show()

我遇到的问题是,我希望图例位于绘图之外,最好位于第二个y轴之后的右侧。这可能吗?现在,图例只是叠加在绘图上,并不完全可见。我曾尝试使用bbox_来_锚定和loc函数,但没有成功。谢谢大家!

ax.get\u legend\u handles\u labels()
收集所有图例句柄及其标签。将这些轴组合起来,可以创建一个新的图例

bbox\u to\u anchor=
使用设置图例的定位点<需要设置code>loc=,以告知图例框的哪个点将被锚固定

导入matplotlib.pyplot作为plt
将numpy作为np导入
作为pd进口熊猫
df=pd.DataFrame({'Date':pd.Date_范围('20210401',句点=30,频率=D'),
“Gas1”:np.random.randn(30.cumsum(),
“Gas2”:np.random.randn(30.cumsum(),
“Gas3”:np.random.randn(30).cumsum(),
“Water1”:np.random.randn(30.cumsum(),
“Water2”:np.random.randn(30.cumsum(),
“Pressure1”:np.random.randn(30).cumsum(),
'Pressure2':np.random.randn(30.cumsum()})
图,ax=plt.子批次()
ax3=ax.twinx()
rspine=ax3.刺['right']
rspine.set_位置((‘轴’,1.15))
ax3.设置帧为on(真)
ax3.patch.set\u可见(False)
图子批次调整(右=0.7)
ax.绘图(df['Date'],df['Gas1'],label=“Gas1”,color='g')
ax.绘图(df['Date'],df['Gas2'],label=“Gas2”,color='b')
ax.plot(df['Date'],df['Gas3'],label=“Gas3”,marker=“o”,markersize=2,color='r')
ax.设定值(“气体速率”)
plt.setp(ax.getxticklabels(),rotation=45,ha='right')
ax2=ax.twinx()
ax2.绘图(df['Date'],df['Water1'],label=“Water1”,color='k')
ax2.绘图(df['Date'],df['Water2'],label=“Water2”,color='y')
ax2.设置标签(“水”)
ax3.绘图(df['Date'],df['Pressure1'],label=“Pressure1”)
ax3.绘图(df['Date'],df['Pressure2'],label=“Pressure2”)
ax3.设置标签(“压力”)
handles1,labels1=ax.get_legend_handles_labels()
handles2,labels2=ax2.get_legend_handles_labels()
handles3,labels3=ax3.get_legend_handles_labels()
ax.图例(手柄=手柄1+手柄2+手柄3,
标签=标签1+标签2+标签3,
bbox_至_锚=(1.28,1.02),位置=(左上角)
plt.紧_布局()
plt.show()