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

如何在Plotly水平条形图中完整显示Y轴长文本内容?

解决Plotly水平条形图Y轴长文本显示不全的问题

可以通过配置Plotly的layout参数调整Y轴布局,完整显示长文本,以下是几种实用方案:

方案1:开启Y轴自动边距推荐

在layout中为Y轴设置automargin: true,Plotly会自动调整左侧边距,确保Y轴标签完整显示:

修改后的布局代码:

var layout = {
  barmode: 'stack',
  yaxis: {
    automargin: true // 自动适配标签长度调整边距
  }
};

方案2:手动设置左侧边距

如果自动边距效果不符合预期,可手动指定左侧边距宽度,给长标签留出足够空间:

var layout = {
  barmode: 'stack',
  margin: {
    l: 220 // 左侧边距设为220px,可根据文本长度灵活调整
  }
};

方案3:让标签自动换行

对于超长文本,也可以设置标签换行显示,通过ticktext插入<br>实现换行:

var layout = {
  barmode: 'stack',
  yaxis: {
    automargin: true,
    tickmode: 'array',
    ticktext: ['giraffes_giraffes_giraffes<br>giraffes_giraffes', 'orangutans', 'monkeys'],
    tickvals: ['giraffes_giraffes_giraffes_giraffes_giraffes', 'orangutans', 'monkeys']
  }
};

完整示例代码方案1

var trace1 = {
  y: ['giraffes_giraffes_giraffes_giraffes_giraffes', 'orangutans', 'monkeys'],
  x: [20, 14, 23],
  name: 'SF Zoo',
  orientation: 'h',
  type: 'bar'
};

var trace2 = {
  y: ['giraffes_giraffes_giraffes_giraffes_giraffes', 'orangutans', 'monkeys'],
  x: [12, 18, 29],
  name: 'LA Zoo',
  orientation: 'h',
  type: 'bar'
};

var data = [trace1, trace2];

var layout = {
  barmode: 'stack',
  yaxis: {
    automargin: true
  }
};

Plotly.newPlot('myDiv', data, layout);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:22:26