Example 5
Synopsis
In this example, we plot monthly car sales of an automobile dealer over a year. Month names are abbreviated. The chart and both axes have a title.
const sales = [20, 19, 14, 17, 20, 18, 13, 11, 15, 12, 16, 18];
const months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
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, give it a title and set its background color.
const context = document.getElementById('chart');
const chart = new LineChart(context);
chart.backgroundColor = 'lightblue';
chart.layout.title = {
text: 'Car Sales',
style: {
color: 'blue',
fontSize: 16,
fontWeight: 'bold'
}
};
Data
We create and style a data series. Then we set the chart's data.
const ds = {
data: sales,
style: {
stroke: 'red'
}
};
chart.data = {
x: months,
y: [ds]
};
Customize
The X-axis is set to display abbreviated months names. The Y-axis shows integer car sales numbers. Both axes have a title.
const ShortMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
chart.layout.xAxis.title.text = 'Month';
chart.layout.yAxis.title.text = 'Sales Number';
chart.layout.xAxis.tick.text = (val) => ShortMonthNames[val - 1];
chart.layout.yAxis.tick.text = (val) => val.toFixed(0);
Plot
We finally call the plot function to display the data.
chart.plot();
Putting it together
HTML
<div id="chart">
</div>
JavaScript
const sales = [20, 19, 14, 17, 20, 18, 13, 11, 15, 12, 16, 18];
const months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const context = document.getElementById('chart');
const chart = new LineChart(context);
chart.backgroundColor = 'lightblue';
chart.layout.title = {
text: 'Car Sales',
style: {
color: 'blue',
fontSize: 16,
fontWeight: 'bold'
}
};
const ds = {
data: sales,
style: {
stroke: 'red'
}
};
chart.data = {
x: months,
y: [ds]
};
const ShortMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
chart.layout.xAxis.title.text = 'Month';
chart.layout.yAxis.title.text = 'Sales Number';
chart.layout.xAxis.tick.text = (val) => ShortMonthNames[val - 1];
chart.layout.yAxis.tick.text = (val) => val.toFixed(0);
chart.plot();