3👍
Solution was simple: replace zero values with null
and add option skipNull: true,
Here struct with data:
var chartDebugData = {
labels: ["2021-11-16", "2021-11-17", "2021-11-18"],
datasets: [
{
label: "Data1",
backgroundColor: "rgba(161, 198, 76, 0.5)",
borderColor: "rgba(161, 198, 76)",
data: [
66,
77,
null,
],
borderWidth: 2,
skipNull: true,
},
{
label: "Data2",
backgroundColor: "rgba(107, 228, 46, 0.5)",
borderColor: "rgba(107, 228, 46)",
data: [
55,
null,
82,
],
borderWidth: 2,
skipNull: true,
},
]
}
JSFiddle: https://jsfiddle.net/tLzhm6p9/
1👍
You can use a custom plugin to go into the propertys before the draw, check if its the only bar if so make it wider and replace it on the chart:
var chartDebugData = {
labels: ["2021-11-16", "2021-11-17", "2021-11-18"],
datasets: [{
label: "Data1",
backgroundColor: "rgba(161, 198, 76, 0.5)",
borderColor: "rgba(161, 198, 76)",
data: [
66,
77,
0,
0
],
borderWidth: 2,
},
{
label: "Data2",
backgroundColor: "rgba(107, 228, 46, 0.5)",
borderColor: "rgba(107, 228, 46)",
data: [
55,
0,
82,
0
],
borderWidth: 2,
},
]
}
const canvasEl = document.getElementById("charts");
// Draw graph
new Chart(canvasEl, {
type: 'bar',
data: chartDebugData,
options: {
barValueSpacing: 5,
},
plugins: [{
beforeDatasetsDraw: (chart, args, opts) => {
const zeroPositions = chart.data.datasets.reduce((acc, curr) => {
curr.data.forEach((dp, i) => {
if (dp === 0) {
acc[i] ? acc[i]++ : acc[i] = 1
}
});
return acc;
}, {});
chart.data.datasets.forEach((d, di) => {
const meta = chart.getDatasetMeta(di);
d.data.forEach((dp, i) => {
if (zeroPositions[i] !== chart.data.datasets.length - 1 || dp === 0) {
return;
}
if (i === 0 && meta.data[i].width !== meta.data[i + 1].width) {
return;
} else if (meta.data[i].width !== meta.data[i - 1].width) {
return;
}
meta.data[i].width = meta.data[i].width * chart.data.datasets.length;
meta.data[i].x = chart.scales.x._labelItems[i].translation[0];
});
});
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.min.js"></script>
<canvas id="charts" width="900" height="450"></canvas>
Source:stackexchange.com