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

Python:Subplot多颜色Barplot无法显示全部图例的解决方法

解决Matplotlib Subplot中Barplot只显示单个图例的问题

你当前的代码通过单次bar()调用绘制所有柱子时,matplotlib会将整组柱子视为单一绘图元素,因此legend()只会识别第一个标签,剩余两个无法显示。以下是两种可行的解决方法:

方法1:拆分绘制每个柱子,单独指定标签

将每个柱子分开绘制,为每个柱子分配对应的颜色和标签,这样matplotlib会为每个柱子生成独立的图例条目:

fig, axs = plt.subplots(2, 3, figsize=(30, 20))
# 提取数据与配置项
categories = df_7_churn_tenure['Kategori']
churn_counts = df_7_churn_tenure['Jumlah Churn']
colors = ['lightsalmon', 'maroon', 'darkorange']
labels = ['Low Tenure = x<24', 'Medium Tenure = 24<= x <=48', 'High Tenure = x >=48']

# 逐个绘制柱子并绑定标签
for idx in range(len(categories)):
    axs[0,1].bar(x=categories[idx], height=churn_counts[idx], color=colors[idx], label=labels[idx])

# 显示图例
axs[0,1].legend(loc='best', fontsize=12)
plt.show()

方法2:手动创建图例补丁(Patch)

如果不想拆分绘制流程,可以通过matplotlib.patches手动创建对应颜色的图例条目,直接添加到图例中:

import matplotlib.patches as mpatches

fig, axs = plt.subplots(2, 3, figsize=(30, 20))
# 绘制所有柱子
axs[0,1].bar(x=df_7_churn_tenure['Kategori'], height=df_7_churn_tenure['Jumlah Churn'], color=['lightsalmon','maroon','darkorange'])

# 生成自定义图例补丁
labels = ['Low Tenure = x<24', 'Medium Tenure = 24<= x <=48', 'High Tenure = x >=48']
colors = ['lightsalmon', 'maroon', 'darkorange']
legend_patches = [mpatches.Patch(color=colors[i], label=labels[i]) for i in range(3)]

# 添加图例到子图
axs[0,1].legend(handles=legend_patches, loc='best', fontsize=12)
plt.show()

两种方法都能完整显示三个图例:

  • 方法1适合需要对单个柱子做额外样式调整的场景;
  • 方法2更简洁,仅用于补全图例时效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:45:41