我是 Javascript 新手,一段时间以来我一直坚持这个问题。我正在尝试循环遍历从烧瓶获得的数据框,并且尝试生成数据框中存在的列的条形图。 (尽管我正在将数据帧转换为在原始代码中列出,但我在这里使用示例数据)。
但是我只得到一个关于 itemData 的第一个元素的图表。我这里哪里出错了?这与画布仅创建一次有关吗?我们将非常感谢您的帮助。
let labels = ['P1', 'P2', 'P3', 'P4', 'P5', 'P6'];
let itemData = [
[12, 13, 14, 15, 16, 17],
[19, 20, 21, 22, 23, 24],
[3, 4, 5, 6, 7, 8],
[5, 6, 7, 8, 9, 10],
[10, 11, 12, 13.14, 15],
[27, 28, 29, 30, 31, 32]
];
let text = ['t1', 't2', 't3', 't4', 't5', 't6'];
for (let i = 0; i < itemData.length; i++) {
const data = {
labels: labels,
datasets: [{
data: itemData[i],
backgroundColor: 'green'
}]
};
const config = {
type: 'bar',
data: data,
options: {
plugins: {
legend: {
display: false
},
title: {
display: true,
text: text[i]
}
}
}
};
const chart = new Chart(
document.getElementById('myChart'),
config
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.2/chart.umd.min.js" integrity="sha512-ziISJqd7FOx3QNvnXiFWAfgSKqte9jMjzhrCnc7Gxpxfxjb5FdrBFg673DloeFEH6VLmTeo86yu5y/xJm38cBg==" crossorigin="anonymous" referrerpolicy="no-referrer">
</script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<div class="container">
<br>
<p><a href="/" class="btn btn-secondary btn">Back to Charts & Analysis</a></p>
<h4>Feature-wise Analysis</h4>
<hr>
</div>
<div style="padding-left: 100px; width: 600px; height: 500px;">
<canvas id="myChart"></canvas>
</div>
您的 HTML 无效。你在体外有div。
您不能在同一画布中放置新图表
const container = document.getElementById('chartContainer')
let labels = ['P1', 'P2', 'P3', 'P4', 'P5', 'P6'];
let itemData = [
[12, 13, 14, 15, 16, 17],
[19, 20, 21, 22, 23, 24],
[3, 4, 5, 6, 7, 8],
[5, 6, 7, 8, 9, 10],
[10, 11, 12, 13.14, 15],
[27, 28, 29, 30, 31, 32]
];
let text = ['t1', 't2', 't3', 't4', 't5', 't6'];
for (let i = 0; i < itemData.length; i++) {
const data = {
labels: labels,
datasets: [{
data: itemData[i],
backgroundColor: 'green'
}]
};
const config = {
type: 'bar',
data: data,
options: {
plugins: {
legend: {
display: false
},
title: {
display: true,
text: text[i]
}
}
}
};
const canvas = document.createElement('canvas');
container.appendChild(canvas)
const chart = new Chart(
canvas,
config
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.2/chart.umd.min.js" integrity="sha512-ziISJqd7FOx3QNvnXiFWAfgSKqte9jMjzhrCnc7Gxpxfxjb5FdrBFg673DloeFEH6VLmTeo86yu5y/xJm38cBg==" crossorigin="anonymous" referrerpolicy="no-referrer">
</script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<div class="container">
<br>
<p><a href="/" class="btn btn-secondary btn">Back to Charts & Analysis</a></p>
<h4>Feature-wise Analysis</h4>
<hr>
</div>
<div id="chartContainer" style="padding-left: 100px; width: 600px; height: 500px;">
</div>