我正在尝试使用Chart.js创建条形图。我希望我的图表看起来像这个示例,其中每个数据集在图表上具有相同的颜色。
但是,就我而言,颜色显示错误。我希望每个类别在图表中共享相同的颜色。
此外,有没有办法将标签(即Category 1
,Category 2
...)放置在日期的每个条下方?
这是我所做的
document.addEventListener('DOMContentLoaded', function () {
const options = {
"type":"bar",
"data":{
"labels":[
"10/25/2021",
"11/1/2021",
"11/8/2021",
"11/15/2021"
],
"datasets":[
{
"label":"Category 1",
"data":[
{
"x":"11/1/2021",
"y":3.25
},
{
"x":"11/8/2021",
"y":3.66
},
{
"x":"11/15/2021",
"y":4.00
}
],
"borderWidth":0,
"backgroundColor":[
"red",
"blue",
"black",
"silver"
]
},
{
"label":"Category 2",
"data":[
{
"x":"11/1/2021",
"y":3.00
},
{
"x":"11/8/2021",
"y":4.00
},
{
"x":"11/15/2021",
"y":5.00
}
],
"borderWidth":0,
"backgroundColor":[
"red",
"blue",
"black",
"silver"
]
},
{
"label":"Category 3",
"data":[
{
"x":"11/1/2021",
"y":2.00
},
{
"x":"11/8/2021",
"y":4.33
},
{
"x":"11/15/2021",
"y":5.00
}
],
"borderWidth":0,
"backgroundColor":[
"red",
"blue",
"black",
"silver"
]
},
{
"label":"Category 4",
"data":[
{
"x":"11/1/2021",
"y":3.25
},
{
"x":"11/8/2021",
"y":4.33
},
{
"x":"11/15/2021",
"y":4.00
}
],
"borderWidth":0,
"backgroundColor":[
"red",
"blue",
"black",
"silver"
]
},
{
"label":"Category 5",
"data":[
{
"x":"11/1/2021",
"y":3.25
},
{
"x":"11/8/2021",
"y":4.00
},
{
"x":"11/15/2021",
"y":5.00
}
],
"borderWidth":0,
"backgroundColor":[
"red",
"blue",
"black",
"silver"
]
},
{
"label":"Category 6",
"data":[
{
"x":"11/1/2021",
"y":3.00
},
{
"x":"11/8/2021",
"y":4.66
},
{
"x":"11/15/2021",
"y":4.00
}
],
"borderWidth":0,
"backgroundColor":[
"red",
"blue",
"black",
"silver"
]
}
]
},
"options":{
"responsive":false,
"plugins":{
"legend":{
"position":"top"
},
"title":{
"display":true,
"text":"Category Overview"
}
}
}
};
let canvas = document.getElementById('chart');
new Chart(canvas.getContext('2d'), options);
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.6.0/dist/chart.min.js"></script>
<canvas width="400" height="400" id="chart"></canvas>