You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib双轴(柱状+折线)图图例标签修改方法求助

解决Matplotlib双轴图表图例修改及版本兼容问题

Hey there! Let's tackle your two questions about Matplotlib and pandas plotting step by step.

1. 自定义双轴图表的图例条目

你的需求是把默认的系列名称(比如A→AA、E→EE)改成自定义名称,这里的关键是要区分**左轴(折线图)和右轴(柱状图)**的图例,因为secondary_y=True会创建一个独立的右侧坐标轴。

推荐写法:绘图时直接指定label

最稳妥的方式是在调用plot()方法时,直接通过label参数定义每个系列的显示名称,这样图例会自动关联正确的系列:

import pandas as pd
import matplotlib
import numpy as np
%matplotlib inline

# 生成测试数据
df = pd.DataFrame(np.random.randint(0,100,size=(20, 5)), columns=list('ABCDE'))

# 绘制右轴柱状图,指定label为'EE'
ax = df[['E']].plot(secondary_y=True, x=df.A, kind='bar', label='EE')
# 绘制左轴折线图,为每个系列指定自定义label
df[['A','B','C','D']].plot(linestyle='-', marker='o', ax=ax, 
                           labels=['AA','BB','CC','DD'])

# 分别设置两个轴的图例位置,避免重叠
ax.legend(loc='upper left')  # 左轴折线图图例
ax.right_ax.legend(loc='upper right')  # 右轴柱状图图例

ax.autoscale(enable=True, axis='both', tight=False)

另一种方式:事后修改图例标签

如果已经完成绘图,也可以通过获取图例对象来修改标签:

# 获取左轴的图例对象
left_legend = ax.legend()
# 修改左轴图例标签
left_legend.set_labels(['AA','BB','CC','DD'])

# 获取右轴的图例对象
right_legend = ax.right_ax.legend()
# 修改右轴图例标签
right_legend.set_labels(['EE'])

2. Matplotlib 2.0.2的TypeError问题解析

你遇到的TypeError: legend() missing 1 required positional argument: 'labels'是因为Matplotlib版本差异导致的API变化:

  • 在Matplotlib 2.0.x版本中,figure.legend()方法要求必须同时传入handles(绘图对象,比如线条、柱状图元素)和labels参数,不能只传labels。
  • 而Matplotlib 2.1+版本优化了这个API,允许只传labels(会自动从当前坐标轴获取handles),所以你升级到2.1版本后问题自动解决。

如果必须在2.0.2版本中使用figure.legend(),可以这样写:

# 先获取所有绘图对象的handles
handles, _ = ax.get_legend_handles_labels()
# 同时传入handles和labels
ax.figure.legend(handles, ['AA','BB','CC','DD'], 
                bbox_to_anchor=(1.,1), loc=1, bbox_transform=ax.transAxes)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:05:37