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

如何为Plotly.js柱状图的X轴柱子添加二级文本?

为Plotly柱状图的X轴柱子添加二级文本

目标效果

目标图表

现有代码

data: Plotly.Data[] = [
    {
      type: 'bar',
      x: ['GHS 1', 'GHS 2', 'GHS 3', 'GHS 4', 'GHS 5'],
      y: [3, 4, 20, 15, 6],
      width: 0.7,
      marker: {
        color: [
          '#FF0000',
          '#FFB340',
          '#FFD940',
          '#95BC28',
          '#009933'
        ]
      }
    }
];

layout = {
    yaxis: {
      showgrid: false,
      showline: true,
      showticklabels: false,
      automargin: true,
      title: {
        text: 'Class Probability',
        standoff: 0
      }
    },
    xaxis: {
    },
    font: { size: 16 },
    width: '100%',
    height: '100%'
  };

当前输出

当前输出图表

解决方案

方法1:利用X轴刻度文本换行(最简单)

直接在X轴的ticktext中使用<br>换行,将主文本和二级文本组合,同时通过tickvals对应原始X轴值:

layout = {
    yaxis: {
      showgrid: false,
      showline: true,
      showticklabels: false,
      automargin: true,
      title: {
        text: 'Class Probability',
        standoff: 0
      }
    },
    xaxis: {
        tickmode: 'array',
        tickvals: ['GHS 1', 'GHS 2', 'GHS 3', 'GHS 4', 'GHS 5'],
        // 用<br>实现换行添加二级文本
        ticktext: [
            'GHS 1<br>Extreme',
            'GHS 2<br>High',
            'GHS 3<br>Medium',
            'GHS 4<br>Low',
            'GHS 5<br>Negligible'
        ],
        tickangle: 0, // 保持文本水平
        tickfont: { size: 14 } // 可按需调整字体大小
    },
    font: { size: 16 },
    width: '100%',
    height: '100%',
    margin: { b: 60 } // 增加底部边距,避免二级文本被截断
  };

方法2:使用Annotations自定义二级文本位置

如果需要更灵活控制文本的位置、样式,可通过annotations配置项添加:

layout = {
    yaxis: {
      showgrid: false,
      showline: true,
      showticklabels: false,
      automargin: true,
      title: {
        text: 'Class Probability',
        standoff: 0
      }
    },
    xaxis: {
    },
    font: { size: 16 },
    width: '100%',
    height: '100%',
    margin: { b: 60 }, // 增加底部边距
    annotations: [
        { x: 'GHS 1', y: -1, text: 'Extreme', showarrow: false, xanchor: 'center', font: { size: 12 } },
        { x: 'GHS 2', y: -1, text: 'High', showarrow: false, xanchor: 'center', font: { size: 12 } },
        { x: 'GHS 3', y: -1, text: 'Medium', showarrow: false, xanchor: 'center', font: { size: 12 } },
        { x: 'GHS 4', y: -1, text: 'Low', showarrow: false, xanchor: 'center', font: { size: 12 } },
        { x: 'GHS 5', y: -1, text: 'Negligible', showarrow: false, xanchor: 'center', font: { size: 12 } }
    ]
  };

两种方法都能实现目标效果,方法1更简洁,方法2适合需要单独调整文本样式或位置的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:25:33