Chart.js使用不同的标签操作图表中的每个条形图


有人知道这是否可能吗?基本上,我希望图表上有标签,例如[Jan,Feb,March],我希望能够打开和关闭这些值。这看起来很简单,但事实证明是有问题的。

您可以为每个条创建一个单独的dataset,并以点格式定义data,如下所示:

data: [{ x: 1, y: 16 }]

此外,您还需要定义第二个包含标签的x轴。

{
offset: true,
gridLines: {
display: false
}
}

第二x轴上的labels需要在每次datasethidden状态改变时以编程方式收集和定义。这可以通过插件核心API来完成。API提供了可用于执行自定义代码的不同挂钩。在您的情况下,可以使用beforeLayout挂钩。

plugins: [{
beforeLayout: chart => chart.chart.options.scales.xAxes[1].labels = chart.chart.data.datasets.filter(ds => !ds._meta[0].hidden).map(ds => ds.label)
}]

请看下面的可运行代码,看看它是如何工作的。

new Chart(document.getElementById('chart'), {
type: 'bar',
plugins: [{
beforeLayout: chart => chart.chart.options.scales.xAxes[1].labels = chart.chart.data.datasets.filter(ds => !ds._meta[0].hidden).map(ds => ds.label)
}],
data: {
datasets: [{
label: 'A',
data: [{ x: 1, y: 16 }],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgb(255, 99, 132)',
borderWidth: 1,
categoryPercentage: 1
},
{
label: 'B',
data: [{ x: 2, y: 22 }],
backgroundColor: 'rgba(255, 159, 64, 0.2)',
borderColor: 'rgb(255, 159, 64)',
borderWidth: 1,
categoryPercentage: 1
},
{
label: 'C',
data: [{ x: 3, y: 18 }],
backgroundColor: 'rgba(255, 205, 86, 0.2)',
borderColor: 'rgb(255, 205, 86)',
borderWidth: 1,
categoryPercentage: 1
},
{
label: 'D',
data: [{ x: 4, y: 13 }],
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgb(75, 192, 192)',
borderWidth: 1,
categoryPercentage: 1
},
{
label: 'E',
data: [{ x: 5, y: 5 }],
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgb(54, 162, 235)',
borderWidth: 1,
categoryPercentage: 1
},
{
label: 'F',
data: [{ x: 6, y: 16 }],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgb(153, 102, 255)',
borderWidth: 1,
categoryPercentage: 1
},
]
},
options: {
tooltips: {
callbacks: {
title: () => undefined
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
display: false
},
{
offset: true,
gridLines: {
display: false
}
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="chart" height="80"></canvas>

最新更新