Issue
I am using Flask and passing data to render a chart. To debug the code, I generate the two value arrays in the JS code. When I run the script, I get only 1 data point. Based on this answer.
<script>
const yVals = [0, 1, 2, 3, 4];
const xVals = [0, 1, 2, 3, 4];
var cv = document.getElementById('lineChart');
var ctx = cv.getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: "Spectrum",
data: yVals.map((v, i) => ({x:xVals[i], y:v})),
backgroundColor: "#33cc33",
borderColor: "#33cc33",
fill: false,
},
]
}
});
</script>
Testing the mapping function in a JS online compiler renders the correct output:
Seems like the ChartJS is not iterating through the whole thing...?
Solution
You are using a default x scale, here chart.js expects strings to be provided for the x axis as label. You are providing numbers. These numbers then get used to point to an index in the labels array, since you are not using that it can't find anything.
The 2 most easy solutions are to make the x values a string or use a linear scale for the x axis:
Strings for X Axis:
const yVals = [0, 1, 2, 3, 4];
const xVals = [0, 1, 2, 3, 4];
var cv = document.getElementById('chartJSContainer');
var ctx = cv.getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: "Spectrum",
data: yVals.map((v, i) => ({
x: `${xVals[i]}`,
y: v
})),
backgroundColor: "#33cc33",
borderColor: "#33cc33",
fill: false,
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.js"></script>
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>
Linear X axis:
const yVals = [0, 1, 2, 3, 4];
const xVals = [0, 1, 2, 3, 4];
var cv = document.getElementById('chartJSContainer');
var ctx = cv.getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: "Spectrum",
data: yVals.map((v, i) => ({
x: xVals[i],
y: v
})),
backgroundColor: "#33cc33",
borderColor: "#33cc33",
fill: false,
}]
},
options: {
scales: {
x: {
type: 'linear'
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.js"></script>
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>
Answered By - LeeLenalee
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.