Highcharts 饼图(Pie Chart)详解
Highcharts 的饼图是最经典的占比展示图表,适合显示一个数据系列中各部分占整体的比例(总和为100%)。它支持普通饼图、半圆饼图(semi-circle donut)、环形图(donut)、3D 饼图等多种变体。
主要类型
- pie:基本饼图
- donut:环形饼图(中间镂空,常用于突出总值)
- 3D pie:立体饼图(需引入 highcharts-3d.js)
1. 基本饼图示例
以下是一个完整的标准饼图示例:
<!DOCTYPEhtml><htmllang="zh"><head><metacharset="UTF-8"><title>Highcharts 饼图示例</title><scriptsrc="https://code.highcharts.com/highcharts.js"></script></head><body><divid="container"style="width:800px;height:600px;margin:50px auto;"></div><script>Highcharts.chart('container',{chart:{type:'pie',// 关键:设置为 'pie'backgroundColor:'#f8f9fa',plotShadow:true// 轻微阴影,提升立体感},title:{text:'2024年浏览器市场份额',style:{fontWeight:'bold',fontSize:'22px'}},subtitle:{text:'数据来源:StatCounter'},tooltip:{pointFormat:'<b>{point.percentage:.1f}%</b>',// 显示百分比percentageDecimals:1},accessibility:{point:{valueSuffix:'%'}},plotOptions:{pie:{allowPointSelect:true,// 允许点击选中扇区cursor:'pointer',// 鼠标悬停显示手型borderRadius:5,// 扇区圆角dataLabels:{enabled:true,// 显示标签format:'<b>{point.name}</b><br>{point.percentage:.1f}%',distance:30,// 标签距离扇区距离style:{fontSize:'14px'}},showInLegend:true// 显示图例(可选)}},series:[{name:'市场份额',colorByPoint:true,// 每个扇区自动不同颜色data:[{name:'Chrome',y:64.8,sliced:true,// 突出显示该扇区selected:true},{name:'Safari',y:19.8},{name:'Edge',y:5.3},{name:'Firefox',y:4.2},{name:'其他',y:5.9}]}]});</script></body></html>2. 环形饼图(Donut Chart)——最常用变体
只需在plotOptions.pie中添加innerSize即可实现环形效果:
plotOptions:{pie:{innerSize:'50%',// 关键:内圈大小(50%~70% 常见)depth:45,// 可选:增加厚度(类似3D效果)dataLabels:{enabled:true,distance:-50,// 标签放在内圈format:'<b>{point.name}</b>: {point.percentage:.1f}%',style:{fontWeight:'bold'}}}},// 可在中心显示总值center:['50%','50%'],// 额外添加中心文本(需自定义)events:{render:function(){// 自定义中心文本示例(可选)letrenderer=this.renderer;lettotal=this.series[0].data.reduce((sum,point)=>sum+point.y,0);if(!this.totalText){this.totalText=renderer.text('总计<br><b>100%</b>',this.plotWidth/2,this.plotHeight/2).css({fontSize:'20px',textAnchor:'middle'}).add();}}}3. 半圆饼图(Semi-circle Donut)
chart:{type:'pie',options3d:{enabled:false}},plotOptions:{pie:{innerSize:'50%',startAngle:-90,// 从顶部开始endAngle:90,// 只画半圆center:['50%','75%']// 下移中心位置}}4. 3D 饼图
需额外引入模块:
<scriptsrc="https://code.highcharts.com/highcharts-3d.js"></script>chart:{type:'pie',options3d:{enabled:true,alpha:45,// 垂直倾斜角beta:0,depth:50// 厚度}},plotOptions:{pie:{depth:50}}5. 常用配置总结
| 配置项 | 说明与推荐值 |
|---|---|
chart.type | ‘pie’ |
plotOptions.pie.innerSize | ‘0%’(实心) / ‘40%-70%’(环形) |
plotOptions.pie.dataLabels | { enabled: true }(强烈推荐开启) |
series.colorByPoint | true(自动分配颜色) |
point.sliced/selected | 突出某个扇区 |
plotOptions.pie.startAngle/endAngle | 控制饼图旋转角度和范围(半圆常用) |
饼图数据必须是单系列,且各点 y 值总和最好为 100(Highcharts 会自动计算百分比)。
如果你需要:
- 多层嵌套环形图(variable pie)
- 点击钻取子饼图(drilldown)
- 自定义颜色主题
- 在 Vue/React 中的封装方式
告诉我具体需求,我可以提供完整代码示例!