Chart.js 支持 混合图(Mixed Chart),可以在同一个图表中组合不同类型的图表(如折线图和柱状图)。
1. 基本混合图
这里是一个 折线图 + 柱状图 的示例:
安装 Chart.js
如果使用 npm:
npm install chart.js
或者直接使用 CDN:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
HTML 代码
<canvas id="myMixedChart"></canvas>
2. JavaScript 代码
<script>
const ctx = document.getElementById('myMixedChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar', // 主类型(柱状图)
data: {
labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
datasets: [
{
type: 'bar', // 柱状图
label: '销售额(万元)',
data: [10, 25, 40, 30, 50, 60],
backgroundColor: 'rgba(75, 192, 192, 0.5)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
},
{
type: 'line', // 折线图
label: '增长率(%)',
data: [5, 15, 25, 10, 30, 45],
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderWidth: 2,
tension: 0.4, // 线条弯曲度
yAxisID: 'y2' // 使用不同的 Y 轴
}
]
},
options: {
responsive: true,
plugins: {
legend: { display: true }
},
scales: {
x: {
title: { display: true, text: '月份' }
},
y: {
title: { display: true, text: '销售额' },
beginAtZero: true
},
y2: {
title: { display: true, text: '增长率(%)' },
position: 'right',
beginAtZero: true,
grid: { drawOnChartArea: false } // 避免两条 Y 轴的网格重叠
}
}
}
});
</script>
3. 进一步优化
添加多个数据集
datasets: [
{
type: 'bar',
label: '产品 A 销售额',
data: [10, 20, 30, 40, 50, 60],
backgroundColor: 'rgba(54, 162, 235, 0.5)'
},
{
type: 'bar',
label: '产品 B 销售额',
data: [15, 25, 35, 45, 55, 65],
backgroundColor: 'rgba(255, 206, 86, 0.5)'
},
{
type: 'line',
label: '增长率',
data: [5, 10, 15, 20, 25, 30],
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2,
tension: 0.4,
yAxisID: 'y2'
}
]
显示数据点
pointRadius: 5, // 数据点大小
pointHoverRadius: 7 // 悬停时数据点大小
添加动画
animation: {
duration: 1000,
easing: 'easeInOutQuart'
}
这样,你就可以在一个图表中同时展示不同类型的数据了!🚀
发表回复