Chart.js is one of the most popular javascript library to display chart and very easy to use
This video will demonstrate how to setup and use chart.js on your website
chart.js supports many types of chart such as Bar, Line, Pie, Radar, Polar and more!
To begin, let's download chart.js and put it to your web directory
Here is the download chart.js and a prepared skeleton HTML file
First, include chart.js
Next, you will need to create a "canvas" This is where our chart will be displayed
You can set width and height of the canvas right away and chart.js will auto-fit the canvas for you
Next, we'll need a javascript to initialize our chart
First, get the canvas element
Then use getContext("2d")
Next, create Chart instance from our canvas 2d context
and call the method of any chart type you'd like. For this tutorial we'll go with Bar chart
And pass the "data" to the method
Let's talk about chart.js data structure... I'll paste an sample of data copied from the chart.js website
The first part of data is "labels" which is our x-axis label. This can be text or numeric
Next is the dataset which can contain one or more sets of data.
The most important part for each set is the "data" array which contains chart value (y-axis)
You also can set a label for each dataset but this is optional
And finally, you can customize the chart color properties
Now our chart is ready. Let's see it in action!
Chart.js will automatically scale the x and y axis interval per data entered
Now let's add another dataset and see the result
(I'll change some color and value for the second dataset)
Since we're using array to supply the chart value, this make it very easy to make our chart "dynamic"
We can dynamically generate an array of data and put it to the dataset to display the chart on the fly
We've covered all the basic for Chart.js but there are mores to come! Stay tune for other "cool" chart.js tutorial!
Thanks for watching! Subscribe for more tutorials and tips!
