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

使用twinx()双Y轴时Seaborn右侧轴图例不显示的解决问询

解决Seaborn lineplot配合twinx()双Y轴图例不显示的问题

当使用Seaborn的lineplot配合Matplotlib的twinx()创建双Y轴图表时,右侧轴的图例无法自动显示——原因是Seaborn默认将图例绑定到初始创建的轴上,而非twinx()生成的独立轴。解决核心是手动收集两个轴的图例元素,再合并显示。

完整实现代码

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

# 生成示例数据
np.random.seed(42)
x = np.arange(1, 11)
df = pd.DataFrame({
    'x': x,
    'y1': np.random.randint(10, 30, size=10),
    'y2': np.random.randint(100, 200, size=10)
})

# 创建主坐标轴
fig, ax1 = plt.subplots(figsize=(8, 5))

# 主轴绘制第一个折线图
sns.lineplot(data=df, x='x', y='y1', ax=ax1, color='blue', label='Y1系列')
ax1.set_ylabel('Y1轴刻度')
ax1.set_xlabel('X轴')

# 创建双Y轴
ax2 = ax1.twinx()

# 双轴绘制第二个折线图(关闭自动图例)
sns.lineplot(data=df, x='x', y='y2', ax=ax2, color='red', label='Y2系列', legend=False)
ax2.set_ylabel('Y2轴刻度')

# 手动合并两个轴的图例
handles1, labels1 = ax1.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(handles1 + handles2, labels1 + labels2, loc='upper left')

plt.tight_layout()
plt.show()

关键步骤说明

  1. 分轴绘制图表:用ax1和twinx()生成的ax2分别承载两个lineplot,第二个图表设置legend=False避免自动生成重复图例。
  2. 收集图例元素:通过get_legend_handles_labels()分别获取两个轴的线条句柄和标签文本。
  3. 合并显示图例:将两组图例元素合并后,调用任意一个轴的legend()方法添加到图表中,位置可通过loc参数调整。

这种方法完全基于Seaborn和Matplotlib的原生API,无需额外工具,就能实现双Y轴各自图例的正常显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 00:58:22