1๐
โ
The scatter chart uses a line chart internally but changes it so the showLine
property becomes false and both axis are set to linear.
So you can just set the showLine
property to false in your dataset and use a line chart.
2๐
You can define your x-axis as follows
x: {
type: 'time',
time: {
parser: 'YYYY-M-D',
unit: 'day',
displayFormats: {
day: 'D MMM YYYY'
},
tooltipFormat: 'D MMM YYYY'
}
}
Further information can be found at the Chart.js documentation here and in the Chart.js samples here.
Note that I use chartjs-adapter-moment together with moment to make this work. The formats for parsing and displaying time values as desired can be found here.
Please take a look at your amended code and see how it works.
var test = [
{ x: "2022-1-8", y: 950 },
{ x: "2022-1-9", y: 1100 },
{ x: "2022-1-10", y: 990 },
{ x: "2022-1-12", y: 1250 },
{ x: "2022-1-13", y: 1050 }
];
var chart = new Chart('chart-line', {
type: 'scatter',
data: {
datasets: [{
data: test,
label: 'buys',
borderColor: "#3e95cd"
}]
},
options: {
responsive: false,
scales: {
x: {
type: 'time',
time: {
parser: 'YYYY-M-D',
unit: 'day',
displayFormats: {
day: 'D MMM YYYY'
},
tooltipFormat: 'D MMM YYYY'
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@1.0.0"></script>
<canvas id="chart-line" height="200"></canvas>
0๐
const data = {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
datasets: [{
label: 'Dataset 1',
data: [{x:1, y:12}, {x:2, y:3}, {x:3, y:2}, {x:4, y:1}, {x:5, y:8}, {x:6, y:8}, {x:7, y:2}, {x:8, y:2}, {x:9, y:3}, {x:10, y:5}, {x:11, y:7}, {x:12, y:1}]
}]
}
const config = {
type: 'scatter',
data,
options: {
responsive: true,
maintainAspectRatio: false,
},
}
const $canvas = document.getElementById('chart')
const chart = new Chart($canvas, config)
<div class="wrapper" style="width: 98vw; height:180px">
<canvas id="chart"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
Source:stackexchange.com