Reputation: 151
Suppose we have the following x-axis values on a chart.js (line) chart: [0,1.9,2,3,4,5]
.
chart.js seems to chart this with the space between 0 and 1.9 being the same as the space between 1.9 and 2?
Is there a simple way to change the behavior (I assume manually setting the tick marks/grid lines would fix this, but perhaps there is an even simpler way?)
<!DOCTYPE html>
<head>
<Title> Chart </Title>
</head>
<body>
<p> Ex chart go</p>
<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: {
}
})
</script>
</body>
</html>
Edit: Let me try to restate my question
Edit 2: Graphics to show what I am asking.
Upvotes: 1
Views: 2774
Reputation: 151
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>
Upvotes: 0
Reputation: 31351
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>
Upvotes: 1