You need to enable JavaScript to run this app. Python matplotlib双y轴绘图pl、ppl图例重叠,用loc调整位置报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python matplotlib双y轴绘图pl、ppl图例重叠,用loc调整位置报错如何解决

提问内容

运行效果

运行效果截图
当前绘制的双Y轴图表中,pl和ppl两个图例在右上角重叠,需求为将其中一个图例移动到左上角。此前尝试使用loc参数调整位置时持续报错,需要解决方案。

原始示例代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.set_xlabel('Date')
ax1.set_ylabel('percent change / 100')
dd = pd.DataFrame(np.random.randint(1,10,(30,2)),columns=['pl','ppl'])
dd['pl'].plot(ax=ax1,legend=True)
dd['ppl'].plot(ax=ax2, style=['g--', 'b--', 'r--'],legend=True)

ax2.set_ylabel('difference')
plt.show()
解决方案

报错原因

pandas的plot()方法中,legend参数仅支持布尔值或配置字典,直接传入loc参数属于参数位置错误,会触发报错。要手动指定图例位置,必须显式调用对应坐标轴的legend()方法,才能传入loc参数。
另外原代码中绘制单条ppl曲线时传入了3个样式值,属于冗余配置,可简化为单样式参数。

两种可行实现方法

方法1:修改现有自动生成的图例位置(无需重写图例配置)

保留原有legend=True的自动生成逻辑,仅在绘图完成后修改指定轴的图例位置即可,代码改动极小:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.set_xlabel('Date')
ax1.set_ylabel('percent change / 100')
dd = pd.DataFrame(np.random.randint(1,10,(30,2)),columns=['pl','ppl'])
dd['pl'].plot(ax=ax1,legend=True)
# 简化style参数为单值,去掉冗余的多配置
dd['ppl'].plot(ax=ax2, style='g--', legend=True)

ax2.set_ylabel('difference')
# 新增代码:将ax1对应的pl图例移动到左上角
ax1.get_legend().set_loc('upper left')
plt.show()

方法2:手动配置图例(灵活性更高)

关闭pandas自动生成的图例,手动调用ax.legend()方法自定义图例的位置、标签、样式等属性:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.set_xlabel('Date')
ax1.set_ylabel('percent change / 100')
dd = pd.DataFrame(np.random.randint(1,10,(30,2)),columns=['pl','ppl'])
# 关闭自动图例
dd['pl'].plot(ax=ax1, legend=False)
dd['ppl'].plot(ax=ax2, style='g--', legend=False)

# 手动指定两个图例的位置
ax1.legend(['pl'], loc='upper left')
ax2.legend(['ppl'], loc='upper right')

ax2.set_ylabel('difference')
plt.show()

常用loc参数可选值

  • upper left:坐标轴左上角
  • upper right:坐标轴右上角(默认值)
  • lower left:坐标轴左下角
  • lower right:坐标轴右下角

内容的提问来源于stack exchange,提问作者user13412850

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.25 23:54:03