Example 1
Synopsis
In this example, we plot the functions x*sin(x)
and x*cos(x)
within the interval [-5π
; +5π
].
The former appears in dashed red line while the latter uses plain blue line.
Values on both axes are shown with 2 decimal places.
A legend is added at the bottom of the chart.
Chart
The chart's context is a div element named 'chart'. Set the size as you want.
<div id="chart">
</div>
We create a line chart and set its background color. We also add a legend at the bottom of the chart and style it.
const context = document.getElementById('chart');
const chart = new LineChart(context);
chart.backgroundColor = 'lightgreen';
chart.layout.legend = {
position: 'south',
textStyle: {
color: 'brown',
fontFamily: 'cursive, sans-serif, "segoe ui"'
},
rectStyle: {
stroke: 'brown',
strokeWidth: 2,
fill: 'white',
cornerRadius: 5
}
};
Data
We create and style two data series. Then we generate X and Y-values for both functions. Finally we set the chart's data.
const sin = {
name: 'x*sin(x)',
data: [],
style: {
stroke: 'red',
strokeDashArray: '2 3'
}
};
const cos = {
name: 'x*cos(x)',
data: [],
style: {
stroke: 'blue'
}
};
let xValues = [];
for (let i = -2000; i <= 2000; i++) {
let x = Math.PI * i / 400;
xValues.push(x);
sin.data.push(Math.sin(x) * x);
cos.data.push(Math.cos(x) * x);
}
chart.data = {
x: xValues,
y: [sin, cos]
};
Customize
We configure the X-axis to show values with 2 decimal places and set the zooming area's background color.
chart.layout.xAxis.tick.text = (val) => val.toFixed(2);
chart.interactivity.zoomRect.fill = 'lightblue';
Plot
We finally call the plot function to display the data.
chart.plot();
Putting it together
HTML
<div id="chart">
</div>
JavaScript
const context = document.getElementById('chart');
const chart = new LineChart(context);
chart.backgroundColor = 'lightgreen';
chart.layout.legend = {
position: 'south',
textStyle: {
color: 'brown',
fontFamily: 'cursive, sans-serif, "segoe ui"'
},
rectStyle: {
stroke: 'brown',
strokeWidth: 2,
fill: 'white',
cornerRadius: 5
}
};
const sin = {
name: 'x*sin(x)',
data: [],
style: {
stroke: 'red',
strokeDashArray: '2 3'
}
};
const cos = {
name: 'x*cos(x)',
data: [],
style: {
stroke: 'blue'
}
};
let xValues = [];
for (let i = -2000; i <= 2000; i++) {
let x = Math.PI * i / 400;
xValues.push(x);
sin.data.push(Math.sin(x) * x);
cos.data.push(Math.cos(x) * x);
}
chart.data = {
x: xValues,
y: [sin, cos]
};
chart.layout.xAxis.tick.text = (val) => val.toFixed(2);
chart.interactivity.zoomRect.fill = 'lightblue';
chart.plot();