0👍
You can use custom chartjs plugin to create the line connector, then draw the line on beforeDatasetsDraw callback using canvas provided by chartjs,
use bar._model.y
to get the top position of each bar
use bar._model.base
to get the bottom position of each bar
var options = {
type: 'bar',
data: {
labels: ["a", "b", "c", "d", "e", "f"],
datasets: [
{
label: 'A',
data: [[12,14], [14,24],[10,12]],
borderWidth: 1
},
]
},
options: {
scales: {
yAxes: [{
ticks: {
reverse: false
}
}]
}
}
}
const barConnector = {
id: 'barConnector',
beforeDatasetsDraw: function(chart, args, plugins){
const { ctx, chartArea } = chart;
ctx.save();
const datasets = chart.config.data.datasets;
datasets.forEach((dataset, datasetIndex) => {
dataset.data.forEach((data, dataIndex) => {
if(dataIndex === dataset.data.length - 1) return;
const bar = chart.getDatasetMeta(datasetIndex).data[dataIndex];
const barX = bar._model.x;
const barY = bar._model.y;
const nextBar = chart.getDatasetMeta(datasetIndex).data[dataIndex + 1];
const nextBarX = nextBar?._model.x;
const nextBarY = nextBar?._model.base;
ctx.beginPath();
ctx.moveTo(barX+46, barY);
ctx.lineTo(nextBarX-46, nextBarY);
ctx.strokeStyle = dataset.backgroundColor;
ctx.lineWidth = 2;
ctx.stroke();
})
});
}
}
options.plugins = [barConnector]
var ctx = document.getElementById('chart-js').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<body>
<canvas id="chart-js" width="600" height="400"></canvas>
</body>
- Chartjs-How can I export data from a csv file or excel file to a javascript object?
- Chartjs-Is there a max width of canvas Chart.js can draw charts within?
Source:stackexchange.com