chart.js:刻度的交替背景色
chart.js: alternating background-color for ticks
我想在带有 chart.js 的条形图中交替使用背景颜色。有一个旧的但已弃用的插件,它确实满足了我的要求 here
repo 底部的第一个示例图片是我需要的。
没有发现任何新东西,也没有发现没有插件的方法。谁能解释一下如何在 chart.js (3.7.0) 的当前版本中实现交替背景?
非常感谢!
这可以使用 chartjs-plugin-annotation 库来完成,如下面的可运行脚本所示。
Detailed information about Box Annotations can be found here
const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
new Chart('chart', {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Dataset 1',
backgroundColor: 'red',
data: [95, 70, 55, -88, -64, 34, -55]
},
{
label: 'Dataset 2',
backgroundColor: 'green',
data: [81, 58, 30, -91, -74, 20, -40]
}
]
},
options: {
plugins: {
annotation: {
annotations: labels
.map((l, i) => ({
drawTime: 'beforeDatasetsDraw',
type: 'box',
xScaleID: 'x',
yScaleID: 'y',
xMin: i - 0.5,
xMax: i + 0.5,
backgroundColor: 'rgba(128, 128, 128, 0.2)',
borderColor: 'rgba(128, 128, 128, 0.4)',
borderWidth: 1
}))
.filter((l, i) => !(i % 2))
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.2.2/chartjs-plugin-annotation.js"></script>
<canvas id="chart" width="300"></canvas>
我想在带有 chart.js 的条形图中交替使用背景颜色。有一个旧的但已弃用的插件,它确实满足了我的要求 here
repo 底部的第一个示例图片是我需要的。 没有发现任何新东西,也没有发现没有插件的方法。谁能解释一下如何在 chart.js (3.7.0) 的当前版本中实现交替背景?
非常感谢!
这可以使用 chartjs-plugin-annotation 库来完成,如下面的可运行脚本所示。
Detailed information about Box Annotations can be found here
const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
new Chart('chart', {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Dataset 1',
backgroundColor: 'red',
data: [95, 70, 55, -88, -64, 34, -55]
},
{
label: 'Dataset 2',
backgroundColor: 'green',
data: [81, 58, 30, -91, -74, 20, -40]
}
]
},
options: {
plugins: {
annotation: {
annotations: labels
.map((l, i) => ({
drawTime: 'beforeDatasetsDraw',
type: 'box',
xScaleID: 'x',
yScaleID: 'y',
xMin: i - 0.5,
xMax: i + 0.5,
backgroundColor: 'rgba(128, 128, 128, 0.2)',
borderColor: 'rgba(128, 128, 128, 0.4)',
borderWidth: 1
}))
.filter((l, i) => !(i % 2))
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.2.2/chartjs-plugin-annotation.js"></script>
<canvas id="chart" width="300"></canvas>