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

如何为Seaborn柱状+折线组合图表添加图例,解决无标签句柄报错

报错原因

该报错是因为你绘制柱状图、折线图时没有给图形对象设置label属性,matplotlib无法识别到可用于图例展示的带标签元素。双轴图的图例还需要手动合并两个坐标轴的句柄,才能同时显示两类图形的图例。

修复方案
  • 给sns.barplot添加label参数,指定柱状图的图例文本
  • 给sns.lineplot添加label参数,指定折线图的图例文本
  • 最后合并两个坐标轴的图例句柄,统一展示
修复后完整代码
from pathlib import Path
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
import numpy as np    

dfGroup = pd.DataFrame({
        'Year': [1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920],
        'Total Deaths': [0, 0, 2, 3, 2, 3, 4, 5, 6, 7, 8],
        'Total Affected': [0, 1, 0, 2, 3, 6, 9, 8, 12, 13, 15]
        })
# Add 3-year rolling average
dfGroup['rolling_3years'] = dfGroup['Total Deaths'].rolling(3).mean().shift(0)
dfGroup = dfGroup.fillna(0)

# Make a smooth line from the 3-year rolling average
from scipy.interpolate import make_interp_spline
X_Y_Spline = make_interp_spline(dfGroup['Year'], dfGroup['rolling_3years'])
 
# Returns evenly spaced numbers over a specified interval.
X_ = np.linspace(dfGroup['Year'].min(), dfGroup['Year'].max(), 500)
Y_ = X_Y_Spline(X_)

# Plot the data
a4_dims = (15, 10)
fig, ax1 = plt.subplots(figsize=a4_dims)

# 新增label参数
ax1 = sns.barplot(x = "Year", y = "Total Deaths",
             data = dfGroup, color='#42b7bd', label='死亡人数')
ax2 = ax1.twinx()
# 新增label参数,显式指定x、y避免新版本seaborn参数警告
ax2 = sns.lineplot(x=X_, y=Y_, marker='o', label='3年滚动平均死亡人数')

# 合并双轴图例,统一显示
handles1, labels1 = ax1.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(handles1 + handles2, labels1 + labels2, loc='upper left')

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:12:03