Highcharts响应式环形图使用labelFormatter自定义图例排版
解决方案
你需要通过关闭默认图例符号渲染、开启HTML自定义标签、手动拼接图例结构的方式实现需求,修改点如下:
- 给
legend配置新增useHTML: true,允许自定义的HTML标签正常渲染 - 将默认图例符号宽度和边距设为0,隐藏系统自动生成的符号
- 在
labelFormatter中手动拼接两行结构,第一行放自定义文本,第二行自行生成符合样式的图例符号+系列名称 - 调整图例项的行高、间距避免排版挤压
修改后的完整配置代码如下:
responsive:{ rules:[{ condition:{ maxWidth: 288 }, chartOptions:{ plotOptions: { pie: { size:'45%', center:[30,70], showInLegend: true } }, legend: { layout: 'horizontal', align:'left', useHTML: true, // 开启HTML渲染支持 symbolWidth: 0, // 隐藏默认符号 symbolPadding: 0, itemStyle: { lineHeight: '20px', // 适配两行高度 fontSize: '12px' }, itemMarginBottom: 8, // 图例项之间留间距 labelFormatter: function () { // 第一行自定义文本可自行替换为需要的内容,示例取y值 const firstLineText = this.options.y // 第二行手动生成图例符号 + 系列名,删除border-radius配置就是方块符号 const secondLine = `<span style="display:inline-block;width:12px;height:12px;border-radius:50%;background-color:${this.color};margin-right:6px;vertical-align:middle;"></span>${this.options.name}` return `<div>${firstLineText}</div><div>${secondLine}</div>` } }, // 其余原有配置保留即可 } }] }
内容的提问来源于stack exchange,提问作者user1637909
相关产品推荐
相关产品推荐

