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

如何在Observable Plot堆叠柱状图顶部显示每组总和?

解决Observable Plot堆叠柱状图顶部显示总和的问题

要在堆叠柱状图的每个柱顶部显示总和,你需要先单独计算每个分类(fundType)的总数值,再用textY标记将总和文本定位到对应柱子的顶部。原代码中使用stackY处理单个堆叠段的文本,只会显示每个分段的数值,无法得到总和。

步骤1:预处理数据计算总和

利用Observable Plot底层依赖的d3工具,用rollup方法按fundType分组计算每组的total总和:

// 计算每个fundType的总数值
const totalByFund = d3.rollup(
  tidy,
  group => d3.sum(group, d => d.total),
  d => d.fundType
);
// 转换为Plot可直接使用的数组格式
const totalData = Array.from(totalByFund, ([fundType, total]) => ({ fundType, total }));

步骤2:修改Plot配置添加总和文本

在marks数组中新增一个textY标记,用预处理后的totalData将总和文本定位到柱子顶部:

var plot2 = oPlot.plot({
  marginBottom: 5,
  width: 928,
  height: 500,
  x: { label: null },
  y: { tickFormat: ".0f", tickSpacing: 20, label: "PRA ($M)", labelAnchor: "center", labelOffset: 40 },
  color: {
    legend: "ramp",
    width: 540,
    label: null,
    range: data.Colors
  },
  marks: [
    oPlot.axisX({ ticks: [] }), // 隐藏X轴刻度
    oPlot.barY(tidy, {
      x: "fundType",
      y: "total",
      insetLeft: 13,
      insetRight: 13,
      fill: "pra",
      sort: { color: null, x: "-y" }
    }),
    // 新增:显示堆叠柱总和的文本标记
    oPlot.textY(totalData, {
      x: "fundType",
      y: "total",
      text: d => d.total.toLocaleString("en-US", {
        minimumFractionDigits: 0,
        maximumFractionDigits: 0
      }),
      textAnchor: "middle", // 文本居中对齐
      dy: -6, // 向上偏移避免与柱子顶部重叠
      filter: d => d.total >= 50 // 过滤小数值不显示
    })
  ]
});

关键说明

  • 原代码的stackY仅用于计算单个堆叠段的位置,无法直接获取整柱总和,因此必须单独汇总数据。
  • 通过dy和textAnchor参数调整文本位置,确保它在柱子顶部居中显示。
  • filter参数延续了你原代码中隐藏小数值的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:00:10