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

Plotly堆叠条形图问题:轨迹显示异常+需添加柱内文本

解决Plotly堆叠条形图的两个问题:trace类型错误与条形内文本添加

问题分析

  1. 第二个trace显示为线条而非堆叠条形:该trace的type被错误设置为"stack",Plotly不支持此trace类型,只有"bar"类型才能配合barmode: 'stack'实现堆叠效果。
  2. 条形内无文本:未给bar trace配置文本相关属性,需添加text字段和文本位置设置才能在条形内部显示内容。
  3. 改用histogram导致日期变为1970年:histogram会自动转换日期为时间戳,处理不当会触发默认纪元时间,因此保持bar类型并正确配置日期轴是更稳妥的方案。

修复步骤

  • 将第二个trace的type改为"bar",与第一个trace类型统一。
  • 为每个trace添加text字段(值对应y轴的日期),设置textposition: 'inside'让文本显示在条形内部,可选配置textfont优化字体样式。
  • 在layout的y轴配置中添加type: 'date',确保日期轴正确渲染。

修改后的完整代码

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv"></div>

<script>
  const traces = [{
      "x": [
        ["FW 10 - 2025", "FW 9 - 2025", "FW 8 - 2025", "FW 7 - 2025", "FW 6 - 2025"],
        ["UnitA", "UnitB", "UnitC", "UnitD", "UnitE"]
      ],
      "y": ['2025-01-01', '2025-03-01', '2025-06-01', '2025-09-01', '2025-12-31'],
      "type": "bar",
      "name": "Unacknowledged",
      "marker": { "color": "#B3C4F3" },
      "text": ['2025-01-01', '2025-03-01', '2025-06-01', '2025-09-01', '2025-12-31'],
      "textposition": "inside",
      "textfont": { "color": "#000", "size": 10 }
    },
    {
      "x": [
        ["FW 10 - 2025", "FW 9 - 2025", "FW 8 - 2025", "FW 7 - 2025", "FW 6 - 2025"],
        ["UnitA", "UnitB", "UnitC", "UnitD", "UnitE"]
      ],
      "y": ['2026-01-01', '2026-03-01', '2026-06-01', '2026-09-01', '2026-12-31'],
      "type": "bar",
      "name": "In Progress",
      "marker": { "color": "#1E4AE9" },
      "text": ['2026-01-01', '2026-03-01', '2026-06-01', '2026-09-01', '2026-12-31'],
      "textposition": "inside",
      "textfont": { "color": "#fff", "size": 10 }
    }
  ];

  const layout = {
    barmode: 'stack',
    xaxis: {
      type: 'multicategory',
      automargin: true
    },
    yaxis: {
      title: 'Date',
      type: 'date'
    },
    template: 'simple_white',
    legend: {
      position: 'bottom',
      y: -.2,
      orientation: 'h'
    }
  };
  Plotly.newPlot('myDiv', traces, layout);
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 05:07:08