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

如何在MP Android中创建单堆叠条形图并将堆叠标签移至右侧?

单堆叠条形图堆叠标签移至右侧的实现方案

当然可行,以Matplotlib为例,你可以通过计算每个堆叠块的右侧位置,在对应位置添加文本标签来实现,具体步骤和代码示例如下:

  • 先绘制基础堆叠条形图,获取各堆叠块的位置与尺寸数据
  • 遍历每个堆叠系列,计算块的右侧x坐标(条形左边界+块宽度),以及垂直居中的y坐标
  • 在计算出的坐标位置添加文本标签

示例代码:

import matplotlib.pyplot as plt

# 示例数据
categories = ['类别A']
series1 = [30]
series2 = [20]
series3 = [50]

# 绘制堆叠条形图
fig, ax = plt.subplots()
bar1 = ax.bar(categories, series1, label='系列1')
bar2 = ax.bar(categories, series2, bottom=series1, label='系列2')
bar3 = ax.bar(categories, series3, bottom=[s1+s2 for s1,s2 in zip(series1,series2)], label='系列3')

# 批量添加右侧标签的函数
def add_right_labels(bars):
    for bar in bars:
        x_pos = bar.get_x() + bar.get_width()  # 堆叠块右侧x坐标
        y_pos = bar.get_y() + bar.get_height() / 2  # 垂直居中y坐标
        ax.text(x_pos, y_pos, f'{bar.get_height()}', va='center', ha='left')

# 给每个堆叠块添加标签
add_right_labels(bar1)
add_right_labels(bar2)
add_right_labels(bar3)

# 调整x轴范围,避免标签被截断
ax.set_xlim(-0.5, 1.2)

plt.legend()
plt.show()

如果使用其他绘图库(如Plotly),核心逻辑一致:找到每个堆叠块的右侧边界坐标,将文本标签放置在该位置即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:30:57