0π
β
To start seeing your data, you have to do the following:
- drop the square parentheses around data generating php, or use some other method to drop one level of square parentheses (js array literal) in the output β
data
should be an array of objects, not an array of arrays of objects.
data: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>,
- delete the
labels
array - add
options.parsing.xAxisKey: 'timestamp'
,options.parsing.yAxisKey: 'generation'
to indicate which property should go to the x axis and which one to the y axis doc link.
With these, youβll get something like:
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'bar',
data: {
//labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: 'Testing',
data: [{"timestamp":"2023-07-04 23:59:02","generation":0},{"timestamp":"2023-07-05 23:59:02","generation":26},{"timestamp":"2023-07-06 23:59:02","generation":28},{"timestamp":"2023-07-07 23:59:02","generation":43},{"timestamp":"2023-07-08 23:59:02","generation":20},{"timestamp":"2023-07-09 23:59:02","generation":32},{"timestamp":"2023-07-11 23:59:02","generation":22},{"timestamp":"2023-07-12 23:59:02","generation":35},{"timestamp":"2023-07-14 23:59:02","generation":8},{"timestamp":"2023-07-15 23:59:02","generation":33},{"timestamp":"2023-07-16 23:59:02","generation":28},{"timestamp":"2023-07-17 16:23:31","generation":35.4},{"timestamp":"2023-07-18 23:00:00","generation":16.2},{"timestamp":"2023-07-19 23:00:00","generation":28},{"timestamp":"2023-07-20 23:00:00","generation":23.9},{"timestamp":"2023-07-21 23:00:00","generation":21.7},{"timestamp":"2023-07-22 23:00:02","generation":14.4}],
borderWidth: 1
}]
},
options: {
parsing: {
xAxisKey: 'timestamp',
yAxisKey: 'generation'
},
scales: {
y: {
beginAtZero: true
}
}
}
});
<canvas id="myChart" style="height:500px"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.0/chart.umd.js" integrity="sha512-CMF3tQtjOoOJoOKlsS7/2loJlkyctwzSoDK/S40iAB+MqWSaf50uObGQSk5Ny/gfRhRCjNLvoxuCvdnERU4WGg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
0π
To resolve this, you should modify the PHP code to directly assign the $dataPoints array without adding an extra level of nesting. Hereβs the updated PHP code:
$dataPoints = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$dataPoints[] = $row['generation']; // Assuming 'generation' is the data point you want to show in the chart
}
}
Source:stackexchange.com