Creating a scatter chart

The type property should be scatter. Scatter charts support the same properties as line charts, but instead of an array of numbers, the data property should contain an array of point objects with the following structure:

{
x: number,
y: number
}

The following example creates a simple scatter chart with a single dataset. The data values consist of a sequence of numbers generated for the x property, and the sine function of each number for the y property:

const dataset = [];
for(let i = 0; i <= 360; i+= 5) {
const point = {
x: i,
y: Math.sin(i * Math.PI / 180)
}
dataset.push(point);
}

const dataObj = {
datasets: [
{
data: dataset,
pointRadius: 2,
backgroundColor: 'red'
}
]
}

const chartObj = {
type: "scatter",
data: dataObj,
options: {
legend: {
display: false
},


}
};
new Chart("my-scatter-chart", chartObj);

You can see the full code in ScatterBubble/scatter-1.html. The result is shown as follows:

A simple scatter chart with x = n and y = sin(x) (code: ScatterBubble/scatter-1.html)

Multiple datasets can be displayed on the same chart. This following example generates two more mathematical functions and displays their graphs using the same scales:

const dataset1 = [], dataset2 = [], dataset3 = [];
for(let i = 0; i <= 360; i+= 5) {
const n = i * Math.PI / 180;
const point1 = { x: n - Math.PI, y: Math.sin(n) }
const point2 = { x: n - Math.PI, y: Math.cos(n) }
const point3 = { x: Math.cos(n) + Math.sin(n), y: Math.cos(n) -
Math.sin(n) }
dataset1.push(point1);
dataset2.push(point2);
dataset3.push(point3);
}

const dataObj = {
datasets: [
{ data: dataset1,
pointRadius: 2,
backgroundColor: 'red'
},{
data: dataset2,
pointRadius: 2,
backgroundColor: 'blue'
},{
data: dataset3,
pointRadius: 2,
backgroundColor: 'green'
}
]
}

const chartObj = {
type: "scatter",
data: dataObj,
options: {
legend: { display: false },
scales: {
yAxes: [{
ticks: {min: -2, max: 2}
}]
}
}
};
new Chart("my-scatter-chart", chartObj);

 You can see the full code in ScatterBubble/scatter-3.html. The result is shown as follows:

Scatterplot with multiple datasets (code: ScatterBubble/scatter-3.html)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.241.199