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

如何在ECharts热力图的X轴数据间添加间距?

解决ECharts热力图X轴标签重叠问题

针对X轴标签相互贴合重叠的问题,给你几个实用的解决办法:

方法1:旋转X轴标签

通过倾斜标签减少横向占用空间,在xAxis配置中添加axisLabel.rotate属性:

xAxis: {
  type: 'category',
  data: hours,
  borderWidth: '10px',
  splitArea: {
    show: true
  },
  axisLabel: {
    rotate: 45 // 可根据需求调整角度,比如30、60
  }
}

方法2:设置标签显示间隔

如果不需要显示所有标签,可通过interval控制显示频率,比如隔一个显示一个:

xAxis: {
  type: 'category',
  data: hours,
  borderWidth: '10px',
  splitArea: {
    show: true
  },
  axisLabel: {
    interval: 2 // 0显示所有,2隔一个显示,也可用函数自定义逻辑
    // 示例:只显示偶数索引的标签
    // interval: function(index) {
    //   return index % 2 === 0;
    // }
  }
}

方法3:调整图表网格边距

给X轴标签预留更多显示空间,修改grid的left和right属性:

grid: {
  height: '50%',
  top: '10%',
  left: '8%', // 增大左侧边距
  right: '8%' // 增大右侧边距
}

方法4:缩小标签字体

减小标签字号节省空间:

xAxis: {
  type: 'category',
  data: hours,
  borderWidth: '10px',
  splitArea: {
    show: true
  },
  axisLabel: {
    fontSize: 10 // 按需调整字号大小
  }
}

完整修改后的代码示例

var dom = document.getElementById('chart-container');
var myChart = echarts.init(dom, null, {
  renderer: 'canvas',
  useDirtyRect: false
});
var app = {};

var option;

// prettier-ignore
const hours = [
    '12a', '1a', '2a', '3a', '4a', '5a', '6a',
    '7a', '8a', '9a', '10a', '11a',
    '12p', '1p', '2p', '3p', '4p', '5p',
    '6p', '7p', '8p', '9p', '10p', '11p'
];
// prettier-ignore
const days = [
    'Saturday', 'Friday', 'Thursday',
    'Wednesday', 'Tuesday', 'Monday', 'Sunday'
];
// prettier-ignore
const data = [[1, 0, 5], [0, 0, 1]]
    .map(function (item) {
    return [item[1], item[0], item[2] || '-'];
});
option = {
  tooltip: {},
  grid: {
    height: '50%',
    top: '10%',
    left: '8%',
    right: '8%'
  },
  xAxis: {
    type: 'category',
    data: hours,
    borderWidth: '10px',
    splitArea: {
      show: true
    },
    axisLabel: {
      rotate: 45,
      fontSize: 10
    }
  },
  yAxis: {
    type: 'category',
    data: days,
    splitArea: {
      show: true
    }
  },
  visualMap: {
    min: 0,
    max: 10,
    calculable: true,
    orient: 'horizontal',
    left: 'center',
    bottom: '15%'
  },
  series: [
    {
      name: 'Punch Card',
      type: 'heatmap',
      data: data,
      label: {
        show: true
      },
      emphasis: {
        itemStyle: {
          margin: 10,
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};
if (option && typeof option === 'object') {
  myChart.setOption(option);
}
window.addEventListener('resize', myChart.resize);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 23:00:25