能否用Highcharts创建带双分类轴的图表?
当然可以用Highcharts创建这种带嵌套双分类底部轴的图表啦!Highcharts原生就支持多级分类轴(Multi-level Categories),刚好能实现你图里的这种嵌套分类效果,下面我给你一个完整的可运行示例,你可以参考调整:
核心实现思路
- 配置x轴时,将
categories设置为嵌套数组,外层元素是父分类,内层数组对应该父分类下的子分类 - 可以通过
xAxis.labels和xAxis.tickPositioner等配置优化分类标签的显示样式,明确区分层级 - 数据系列的点会自动对应到最内层的子分类上
完整示例代码
Highcharts.chart('container', { chart: { type: 'bar' // 可根据需求改成column或其他图表类型 }, title: { text: '嵌套双分类轴示例' }, xAxis: { categories: [ ['Group A', 'Item 1'], ['Group A', 'Item 2'], ['Group A', 'Item 3'], ['Group B', 'Item 1'], ['Group B', 'Item 2'], ['Group B', 'Item 3'], ['Group C', 'Item 1'], ['Group C', 'Item 2'] ], labels: { align: 'right', formatter: function() { // 子分类显示具体项,父分类通过自定义tickPositioner来添加 return this.value[1] || this.value[0]; }, style: function() { // 给父分类标签设置加粗样式,区分层级 return this.value.length === 1 ? { fontWeight: 'bold', fontSize: '14px' } : {}; } }, tickPositioner: function() { const positions = []; const categoryGroups = {}; const categories = this.categories; // 先添加所有子分类的tick位置 categories.forEach((_, idx) => positions.push(idx)); // 计算父分类的居中tick位置 categories.forEach((cat, idx) => { const parent = cat[0]; if (!categoryGroups[parent]) { categoryGroups[parent] = { start: idx }; } categoryGroups[parent].end = idx; }); // 将父分类的居中位置加入tick列表 Object.values(categoryGroups).forEach(group => { const centerPos = (group.start + group.end) / 2; positions.push(centerPos); }); return positions.sort((a, b) => a - b); }, tickLength: 0, lineWidth: 1 }, yAxis: { min: 0, title: { text: '数值' } }, legend: { reversed: true }, plotOptions: { series: { stacking: 'normal' } }, series: [{ name: 'Series 1', data: [5, 3, 4, 7, 2, 5, 3, 6] }, { name: 'Series 2', data: [2, 2, 3, 2, 1, 4, 2, 3] }] });
额外样式优化提示
- 如果想给父分类添加背景色块,可以用Highcharts的
renderer.rect()方法手动绘制,增强层级视觉区分 - 可通过
xAxis.gridLinePositions控制网格线仅显示在子分类位置,让图表更整洁 - 若需要调整分类标签的间距,可修改
xAxis.labels.padding属性
内容的提问来源于stack exchange,提问作者Boosted_d16
相关产品推荐
相关产品推荐

