I have a script that uses ChartJS for plotting the performance of a QR code in term of scans and unique users. The chart only plots interactions with the QR, skipping those days when there is no interaction with it.
I would like to include those days plotting 0 as value for that day in case no interaction happens. Any suggestion on how to achieve this?
this is the code:
/* Display chart */
new Chart(pageviews_chart, {
type: 'line',
data: {
labels: <?= $data->pageviews_chart['labels'] ?>,
datasets: [
{
label: <?= json_encode(l('link_statistics.pageviews')) ?>,
data: <?= $data->pageviews_chart['pageviews'] ?? '[]' ?>,
backgroundColor: pageviews_gradient,
borderColor: pageviews_color,
fill: true
},
{
label: <?= json_encode(l('link_statistics.visitors')) ?>,
data: <?= $data->pageviews_chart['visitors'] ?? '[]' ?>,
backgroundColor: visitors_gradient,
borderColor: visitors_color,
fill: true
}
]
},
options: chart_options
});
thank you!
My Answer:
To include zero values for days with no interaction, you can modify the data array before passing it to the ChartJS dataset. Here's an example of how you can achieve this:
javascript
/* Display chart */
new Chart(pageviews_chart, {
type: 'line',
data: {
labels: = $data->pageviews_chart['labels'] ?>,
datasets: [
{
label: = json_encode(l('link_statistics.pageviews')) ?>,
data: fillZeroValues($data->pageviews_chart['pageviews']),
backgroundColor: pageviews_gradient,
borderColor: pageviews_color,
fill: true
},
{
label: = json_encode(l('link_statistics.visitors')) ?>,
data: fillZeroValues($data->pageviews_chart['visitors']),
backgroundColor: visitors_gradient,
borderColor: visitors_color,
fill: true
}
]
},
options: chart_options
});
function fillZeroValues(data) {
let filledData = [];
let labels = = json_encode($data->pageviews_chart['labels']) ?>;
labels.forEach((label, index) => {
let value = data[index] || 0;
filledData.push(value);
});
return filledData;
}
In this code snippet, the `fillZeroValues` function takes the original data array and fills in zero values for days with no interaction based on the labels array. This ensures that the chart will display zero values for days without any interaction.
Rate this post
4 of 5 based on 1821 votesComments