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

如何在Google Colab中基于数组数据绘制段数不等的横向堆叠条形图

解决方案

你不需要额外引入其他库,直接用Matplotlib就能实现该需求,核心逻辑是放弃批量绘制所有条形同位置分段的写法,改为逐根条形单独绘制它的所有分段即可。你要搜索相关内容的话,对应的关键词是不等分段堆叠条形图,英文关键词为stacked bar chart with variable number of segments per bar。

实现代码

import matplotlib.pyplot as plt
import numpy as np

# 定义数据:每个子列表对应一根条形的所有分段长度,不同子列表长度可以不同
bar_segments = [
    [20, 15, 10],  # 第一根条形:3段
    [35, 32],       # 第二根条形:2段
    [10, 20, 15, 19], # 第三根条形:4段
    [35]            # 第四根条形:1段
]
bar_labels = ["条形1", "条形2", "条形3", "条形4"]
n_bars = len(bar_segments)
y_pos = np.arange(n_bars)
bar_height = 0.6

fig, ax = plt.subplots()

# 逐根绘制条形
for y, segments in zip(y_pos, bar_segments):
    left = 0
    for seg_len in segments:
        # 绘制单个分段
        rect = ax.barh(y, seg_len, height=bar_height, left=left)
        # 给分段加中心标签
        ax.bar_label(rect, label_type='center')
        # 更新下一段的起始位置
        left += seg_len

# 配置图表
ax.set_ylabel('Bars')
ax.set_title('Divisions of each bars')
ax.set_yticks(y_pos, labels=bar_labels)

plt.show()

说明

这种写法可以自由调整每根条形的分段数量,你只需要把自己数组里存的源数据整理成上述代码中bar_segments的格式即可,不需要做额外的对齐补全处理。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:42:03