1👍
✅
Default scale type for the X axis is category
this takes all labels and makes it a datapoint, if you change the scale type to linear
you will get what you want.
Example:
<div>
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById(`myChart`);
const xval = [0, 1.9, 2, 3, 4, 5];
const yval = [10, 8, 6, 4, 2, 0]
const toPlot = {
labels: xval,
datasets: [{
label: "Ex chart",
data: yval,
fill: false
}]
};
let myChart = new Chart(ctx, {
type: `line`,
data: toPlot,
options: {
scales: {
x: {
type: 'linear',
ticks: {
stepSize: 1 // remove this line to get autoscalling
}
}
}
}
})
</script>
0👍
Here is a way to do it with a scatter plot, and setting showLine: True
(maybe some other random stuff thrown in there that does nothing useful, sorry. been messing with the code)
(note: data needs to be in a different format for scatter)
<div>
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById(`myChart`);
// const xval = [0,1.9,2,3,4,5];
// const yval = [10,8,6,4,2,0]
const scatterData = [{
x: 0,
y: 10
}, {
x: 1.9,
y: 8
}, {
x: 2,
y: 6
}, {
x: 3,
y: 4
}, {
x: 4,
y: 2
}, {
x: 5,
y: 0
}]
const toPlot = {
// labels:xval,
datasets: [{
// label: "Ex chart",
data: scatterData,
fill: false,
showLine: true,
}]
};
let myChart = new Chart(ctx, {
type: `scatter`,
data: toPlot,
options: {
responsive: true,
plugins: {
title: {
display: true,
text: 'Chart.js Line Chart'
},
},
interaction: {
mode: 'index',
intersect: false
},
scales: {
x: {
display: true,
title: {
display: true,
text: 'Month'
},
min: 0,
max: 5,
},
y: {
display: true,
title: {
display: true,
text: 'Value'
},
min: 0,
max: 10,
}
}
},
})
</script>
Source:stackexchange.com