要将Chart.js图表分成两行显示,而不是堆叠在一列中,你可以使用HTML和CSS来控制布局。以下是一个基本的示例,展示了如何实现这一点:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chart.js Two Rows Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="chart-container">
<div class="chart-row">
<canvas id="chart1"></canvas>
</div>
<div class="chart-row">
<canvas id="chart2"></canvas>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="script.js"></script>
</body>
</html>
/* styles.css */
.chart-container {
display: flex;
flex-direction: column;
}
.chart-row {
display: flex;
justify-content: space-around;
margin-bottom: 20px;
}
#chart1, #chart2 {
width: 45%;
height: 300px;
}
// script.js
document.addEventListener('DOMContentLoaded', function() {
var ctx1 = document.getElementById('chart1').getContext('2d');
var myChart1 = new Chart(ctx1, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
var ctx2 = document.getElementById('chart2').getContext('2d');
var myChart2 = new Chart(ctx2, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
options: {}
});
});
<canvas>
元素的容器,每个<canvas>
元素用于绘制一个图表。.chart-container
设置为垂直排列的Flex容器,.chart-row
设置为水平排列的Flex容器,使得每个图表在其行中均匀分布。<canvas>
元素上。这种布局适用于需要在有限空间内并排显示多个图表的场景,例如仪表板、数据分析页面等。
通过这种方式,你可以有效地将图表分成两行显示,而不是堆叠在一列中。
领取专属 10元无门槛券
手把手带您无忧上云