Chart.js 极地图(Polar Area Chart)
极地图(Polar Area Chart)是一种用于比较多个类别的图表,类似于饼图,但数据点的半径不同,可以更好地展示数据的比例差异。
1. 安装 Chart.js
如果你使用 npm:
npm install chart.js
或者直接通过 CDN 引入:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
2. HTML 代码
<canvas id="myPolarChart"></canvas>
3. JavaScript 代码
<script>
const ctx = document.getElementById('myPolarChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'polarArea', // 极地图类型
data: {
labels: ['苹果', '香蕉', '橘子', '葡萄', '蓝莓'],
datasets: [{
label: '水果销量(千吨)',
data: [35, 20, 40, 25, 30], // 各类别的值
backgroundColor: [
'rgba(255, 99, 132, 0.5)', // 苹果
'rgba(255, 206, 86, 0.5)', // 香蕉
'rgba(54, 162, 235, 0.5)', // 橘子
'rgba(75, 192, 192, 0.5)', // 葡萄
'rgba(153, 102, 255, 0.5)' // 蓝莓
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(255, 206, 86, 1)',
'rgba(54, 162, 235, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
legend: { display: true } // 显示图例
},
scales: {
r: { // r 轴是极地图的半径轴
beginAtZero: true, // 从 0 开始
angleLines: { display: true }, // 显示角度线
suggestedMin: 0, // 最小值
suggestedMax: 50 // 最大值
}
}
}
});
</script>
4. 进一步优化
增加多个数据集
可以在 datasets
数组中添加多个数据集:
datasets: [
{
label: '2024 年',
data: [30, 25, 35, 20, 40],
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
},
{
label: '2023 年',
data: [20, 15, 25, 30, 35],
backgroundColor: 'rgba(54, 162, 235, 0.5)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}
]
调整动画
animation: {
duration: 1500,
easing: 'easeOutBounce'
}
这样,你就可以在网页上绘制一个美观的极地图了!🚀
发表回复