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

如何为ggplot2中两组geom_bar堆叠柱状图设置独立图例?

堆叠柱状图双独立图例实现方案

核心思路

分别获取两组数据集的绘图元素,独立创建两个图例并指定不同位置,避免互相覆盖。以下以Matplotlib为例给出具体代码:

步骤1:绘制堆叠柱并保存绘图元素

import matplotlib.pyplot as plt
import numpy as np

# 假设x_axis是你的横轴标签数组,比如[0,1,2,...]或分类标签
x_axis = np.arange(len(my_reorganised_data.index))

# 绘制第一组(n_1至n_26)堆叠柱,保存所有patch
n_patches = []
bottom = np.zeros(len(x_axis))
for col_name, col_data in my_reorganised_data.items():
    bar = plt.bar(x_axis, col_data, bottom=bottom)
    n_patches.extend(bar)
    bottom += col_data

# 绘制第二组(其他名称标签)堆叠柱,保存所有patch
p_patches = []
bottom = np.zeros(len(x_axis))
for col_name, col_data in p_bars.items():
    bar = plt.bar(x_axis, col_data, bottom=bottom)
    p_patches.extend(bar)
    bottom += col_data

步骤2:添加双独立图例

# 创建第一组图例,指定位置避免重叠
leg_n = plt.legend(n_patches, my_reorganised_data.columns, title='N系列', bbox_to_anchor=(1.02, 1), loc='upper left')
# 必须手动添加第一个图例到轴上,否则第二个会覆盖它
plt.gca().add_artist(leg_n)

# 创建第二组图例,放在第一组下方
plt.legend(p_patches, p_bars.columns, title='其他系列', bbox_to_anchor=(1.02, 0.4), loc='upper left')

步骤3:调整布局避免图例截断

# 给右侧留出足够空间放图例
plt.subplots_adjust(right=0.7)
plt.show()

其他库适配提示

如果用Seaborn或Plotly,核心逻辑不变:

  • Seaborn:通过获取每个条形的patch对象来创建自定义图例
  • Plotly:在layout里配置两个legend对象,分别对应两组数据的showlegend属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:14:52