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

如何让Highcharts中的系列文本实现响应式自动换行?

Highcharts 数据标签响应式自动换行解决方案

要解决数据标签文本因屏幕缩小重叠的问题,可通过以下两种方式实现自动换行:

方法一:CSS样式强制换行(推荐)

在plotOptions.column.dataLabels中开启HTML支持,并通过CSS样式设置换行规则,让文本根据容器宽度自动换行:

plotOptions: {
  column: {
    stacking: 'normal',
    dataLabels: {
      enabled: true,
      useHTML: true, // 开启HTML支持以生效CSS样式
      style: {
        color: 'black',
        fontSize: '13px',
        textShadow: 'none',
        whiteSpace: 'normal', // 允许文本自动换行
        width: '80px', // 限制标签宽度,超出自动换行
        wordBreak: 'break-all' // 针对无空格长文本强制拆分
      },
      backgroundColor: 'rgba(0, 0, 0, 0)',
      formatter: function() {
        return this.series.name + ': ' + Highcharts.numberFormat(this.y, 0) + '%';
      }
    }
  }
},

方法二:格式化函数手动控制换行

如果需要精准控制换行位置,可在formatter函数中对长文本拆分并插入<br>标签(需配合useHTML: true):

formatter: function() {
  // 示例:每6个字符插入一次换行
  const splitName = this.series.name.replace(/(.{6})/g, '$1<br>');
  return splitName + ': ' + Highcharts.numberFormat(this.y, 0) + '%';
}

修改后的完整代码

// container7
var chartOptions = {
  chart: {
    type: 'column',
    inverted: true,
    height: 200
  },
  title: {
    text: ''
  },
  xAxis: {
    lineColor: 'white',
    categories: ['ABCD'],
    labels: {
      padding: 40,
      style: {
        fontSize: '12px'
      }
    }
  },
  yAxis: {
    allowDecimals: false,
    max: 100,
    title: {
      text: ''
    },
    labels: {
      enabled: false
    },
    gridLineWidth: 0
  },
  plotOptions: {
    column: {
      stacking: 'normal',
      dataLabels: {
        enabled: true,
        useHTML: true,
        style: {
          color: 'black',
          fontSize: '13px',
          textShadow: 'none',
          whiteSpace: 'normal',
          width: '80px',
          wordBreak: 'break-all'
        },
        backgroundColor: 'rgba(0, 0, 0, 0)',
        formatter: function() {
          return this.series.name + ': ' + Highcharts.numberFormat(this.y, 0) + '%';
        }
      }
    }
  },
  colors: ['#d37295', '#fabfd2'],
  series: [{
    name: 'LLLL!LLLL!LLLL!LLLL!LLLL!LLLL!LLLL!',
    data: [57]
  }, {
    name: 'XYZM XYZMXYZMXYZMXYZM XYZMXYZM XYZM XYZM',
    data: [43]
  }],
  legend: {
    enabled: false
  },
  credits: {
    enabled: false
  }
};

// Render the chart using Highcharts
Highcharts.chart('container7', chartOptions);
<script src="https://code.highcharts.com/highcharts.js"></script>
<h2>... look like this:</h2>
<div id="container7" style=" border: 1px solid lightgray;"></div>

说明:whiteSpace: 'normal'允许文本自动换行,width限制标签最大宽度,wordBreak: 'break-all'确保无空格的连续字符串也能被强制拆分,适配不同屏幕尺寸。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 18:58:09