如何使用React Highcharts实现目标环形图(Doughnut Chart)?
如何实现独立分段的环形图?
我想要实现的是独立分段的环形图(如下预期效果):
但实际生成的却是普通的环形饼图:
以下是我使用React Highcharts编写的代码:
const getOptions = (type) => ({ chart: { type:'pie', width: 500, height: 300, }, title: { text: _.startCase(`${type} chart`), }, plotOptions: { series: { borderWidth: 0 }, type: 'pie', size: '100%', innerSize: '90%', dataLabels:{ distance: '-20px' } }, legend: { enabled: false }, credits: { enabled: false }, yAxis: { title: { text: 'Values', }, }, colors: ['#FCE700', '#F8C4B4', '#f6e1ea', '#B8E8FC', '#BCE29E'], series: [ { data: [{ y: 61.41, selected: true },{ y: 20, selected: true } ], size: '100%', innerSize: '80%', dataLabels: { enabled: false, labelConnector: false, } }, ], }); function App() { return ( <div> <HighchartsReact highcharts={Highcharts} options={getOptions('pie')} /> </div> ); }
解决方法
你要的这种独立分段的环形图,不能用单个饼图series实现,得把每个分段做成独立的series,每个series只放一个数据,再通过startAngle和endAngle控制每个分段的角度范围,同时统一所有series的内外半径,就能做出预期效果。
修改后的代码如下:
const getOptions = (type) => ({ chart: { type: 'pie', width: 500, height: 300, }, title: { text: _.startCase(`${type} chart`), }, plotOptions: { pie: { borderWidth: 0, size: '100%', innerSize: '80%', dataLabels: { enabled: false } } }, legend: { enabled: false }, credits: { enabled: false }, colors: ['#FCE700', '#F8C4B4'], // 对应两个分段的颜色 series: [ // 第一个分段:占61.41% → 360*0.6141≈221度 { type: 'pie', data: [{ y: 61.41 }], startAngle: 0, endAngle: 221, size: '100%', innerSize: '80%' }, // 第二个分段:占20% → 360*0.2=72度,和前一段留10度间隔 { type: 'pie', data: [{ y: 20 }], startAngle: 231, endAngle: 231 + 72, size: '100%', innerSize: '80%' } ], }); function App() { return ( <div> <HighchartsReact highcharts={Highcharts} options={getOptions('pie')} /> </div> ); }
核心调整点:
- 把每个环形段拆成独立的
series,每个series只存一个数据项 - 给每个series设置
startAngle(起始角度)和endAngle(结束角度),按需控制分段长度和间隔 - 所有series用相同的
size和innerSize,保证环形的粗细一致 - 删掉了没用的
selected属性和饼图不需要的yAxis配置
要加更多分段的话,照着这个逻辑新增series,算好角度范围就行。
内容的提问来源于stack exchange,提问作者pranathi tammina
相关产品推荐
相关产品推荐

