At one end of the spectrum morris.js from Olly Smith provides a simple way to create very nice charts.
At the other end D3.js is a very sophisticated package for working with data that includes charts among a wide range of displays.
In this tutorial I am going to use Highcharts to draw a typical Line Graph that will look like this:
Step by Step
There are so many options available for Highcharts that the best way to get started is to copy one of their many Highcharts Demos, replace their data with your own and then changing the options to suit your chart.
Understanding the Code
There are four parts to this block of code. The first two script tags load the core highcharts.js library and an extra module exporting.js which allows you to download different representations of the chart.
The div is a placeholder for the graph once we create it. The width and height values define the size of the graph.
All our configuration takes place in the final script block. A wrapper function is defined which calls the highcharts function on the container div.
The parameters passed to the highcharts function are a series of hashes, each named after the component that we want to define. So we have title, xAxis,yAxis, series, etc.
series specifies the data that we want to plot. It takes an array of series - but here we have only one. Each series is a hash with a name and an array of data values.
xAxis specifies the categories or values used to mark this axis. In this example these are months.
yAxis in this example is pretty minimal. Highcharts will figure out the min and max values based on the actual data. In this case I want to override the min value, setting it to 0.I specify a title for the axis and draw some horizontal lines.
For a basic chart, that is pretty much it - the other options create a title and hide the legend. Note that you don't need to define any colors, fonts, etc. as Highcharts has a good set of defaults.
You can customize just about anything if you choose to. Look at the extensive Highcharts Documentation and API Reference
Go to the demo page and mouse over the data points. You will see tooltips that show specific data values. Click on the icon in the top right of the chart and look at the available options for downloading the chart in various formats. All of this comes as part of the library with no extra code or configuration necessary.
Highcharts is really a very nice library to work with. Check out the Highcharts Demos to find the one that suits your application.
Then click on Edit in jsFiddle to get an editor loaded with that example. Try changing some of the options and click Run to see the updated graph.
Finally, please take a second look at that graph - those numbers are REAL - the humanitarian crisis in Syria is getting worse every day.
Please consider a donation to Doctors Without Borders to help out. - thanks --Rob
Code for this Tutorial
Share this tutorial
Comment on this Tutorial
comments powered by Disqus