Plotly堆叠条形图问题:轨迹显示异常+需添加柱内文本
解决Plotly堆叠条形图的两个问题:trace类型错误与条形内文本添加
问题分析
- 第二个trace显示为线条而非堆叠条形:该trace的
type被错误设置为"stack",Plotly不支持此trace类型,只有"bar"类型才能配合barmode: 'stack'实现堆叠效果。 - 条形内无文本:未给bar trace配置文本相关属性,需添加
text字段和文本位置设置才能在条形内部显示内容。 - 改用
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
相关产品推荐
相关产品推荐

