Getting Started with JavaScript Charts
by
, 03-18-2016 at 04:41 AM (19044 Views)
Credits: This is a guest post by Rohit Boggarapu, a software engineer at Adobe.
Data visualization is something that comes up at least once in the work life of a frontend developer. If you are a JavaScript developer and haven’t made any interactive charts yet, then there is a good chance that you will do so in near future. And to prepare you for that moment, I decided to write this detailed tutorial.
In this tutorial I will not only cover the process of making a simple chart in JavaScript using FusionCharts, but I will also go over some advanced topics like ‘using theme manager’ and ‘adding event handlers’.
I have divided the tutorial into three sections:
Section 1: Making a JavaScript chart - 2 step process
Section 2: Making it look better
Section 3: Adding event handlers
If you need source code to follow along, you can get it from this demo on JSFiddle that I made for the tutorial.
Section 1: Making a JavaScript Chart - 2 Step Process
FusionCharts offers more than 90 charts out of the box, and you can make any chart out of those using a simple two step process:
1.a Including Dependencies and Creating Chart Container
First we need to include all the JavaScript files our project is dependent on. In our case we need only two files - `fusioncharts.js` and `fusioncharts.charts.js` - which you can download from here. Once we have the files included, we need to make a `<div>` container to house our chart.
Here’s how we achieve above goals:
1.b Creating Chart Instance and Rendering the ChartCode:<html> <head> // fusioncharts core library <script type="text/javascript" src="fusioncharts.js"></script> <script type="text/javascript" src="fusioncharts.charts.js"></script> </head> <body> <!-- container for our chart --> <div id="donut-chart">Donut chart is coming!</div> // we will fill this script tag in next step <script type="text/javascript"></script> </body> </html>
Next step is to create an instance of the chart with type as `doughnut2d
`, set dimension (`width
` and `height
`), and finally specify the data format and data source being used in the chart.
Here’s the code for that (explanation after snippet):
In the above code we:Code:var revenueChart = new FusionCharts({ type: "doughnut2d", renderAt: "donut-chart", width: "100%", height: "500", dataFormat: "json", dataSource: { "chart": { "caption": "Acme Inc's 2015 Revenue Split", "numberPrefix": "$", "use3DLighting": "0", "showPercentValues": "1", "showLegend": "1", "defaultCenterLabel": "Total revenue: $64.08K", "centerLabel": "Revenue from $label: $value", "decimals": "0" }, "data": [{ "label": "Food", "value": "28504" }, { "label": "Apparels", "value": "14633" }, { "label": "Electronics", "value": "10507" }, { "label": "Household", "value": "4910" }] } });
- Created FusionCharts instance and assigned it to `revenueChart
` variable.
- Set the chart `type
` as `doughnut2d
` since we are plotting a doughnut chart. Each chart in FusionCharts has a unique alias which you can search in this chart list page.
- Assigned `renderAt
` the id of `<div>
` container where we want to render our chart.
- Defined `width
`, `height
`, `dataFormat
` for the chart - which are self explanatory.
-Filled `dataSource
` with content for the chart. Chart’s cosmetics went inside `chart` object and the actual data being plotted went inside `data` object as `label` and `value` pairs.
After above code, we just need to call `render` method on `revenueChart` to render the chart in our HTML container:
To make sure charting library loads before we start using it, we can wrap above code inside `Code:revenueChart.render();FusionCharts.ready()
` like this:
Code:FusionCharts.ready(function() { var revenueChart = new FusionCharts({ // chart content goes here as // shown in above snippets }); revenueChart.render(); });
After you do everything as described above, you will get a chart like this:
I know it is a bit ugly, and to make it beautiful, let’s explore section 2.
Section 2: Making It Look Better
Every charting library offers some way to customize design and functionality of its charts. In FusionCharts this ability is delivered through ‘chart attributes’. You can do almost any type of design changes using hundreds of attributes that are available for a chart.
To know which chart attributes apply to a particular chart, just visit this page: http://www.fusioncharts.com/dev/chart-attributes.html, and type the name of the chart that you want to customize.
Below I have explained two ways in which you can customize design using chart attributes.
2.a Directly Through Chart Attributes
If you want to customize your charts just a little, then this is the best way. By ‘just a little’ I mean if you are including a single chart in your page and want to modify 10-15 attributes to improve the design.
If that is your requirement, then you can directly set the chart attributes and its values inside the `chart` object. You can see some of the values that I have used in our chart in this code snippet:
Here is some explanation for the same:Code:"chart": { "caption": "Acme Inc's 2015 Revenue Split", "numberPrefix": "$", "showPercentValues": "1", "showLegend": "1", "defaultCenterLabel": "Total revenue: $64.08K", "centerLabel": "Revenue from $label: $value", "decimals": "0" // more chart attributes }
-`caption
` is used to define chart title. It is ‘Acme Inc's 2015 Revenue Split’ in our example
-`numberPrefix
`, as the name suggests, sets the prefix for numbers used in the chart. We are prefixing our numbers with `$`.
You can use `showLegend
` to enable or disable legend for the chart. Value of 1 means legend will be shown.
Other labels used above are self-explanatory, but if you are not sure about anything, please visit chart attributes page for doughnut chart.
2.b Using Theme Manager File
This is another way to customize your chart using chart attributes. Method of using attributes remains same, but instead of placing the attributes in the same file you place them inside a separate file and then include that file via `<script>
` tag.
This is how a theme file looks like:
To use the attributes defined in this file you will have to include it in HTML and set the value for the theme attribute to the `Code:FusionCharts.register('theme', { name: "javascript-kit", theme: { base: { chart: { "captionFontSize": "23", "captionFontBold": "0", "baseFont": "Open Sans", "baseFontSize": "14", "xAxisNameFontBold": "0", // more chart attributes } } } });name
` you set here. In our case it will look like:
You will find this useful if you have to manage many charts as this allows you to control cosmetics of your charts centrally. To explore more you can visit this documentation page.Code:"chart": { "theme": "javascript-kit", // more chart attributes }
Section 3: Adding Event Handlers
First two sections above covered the basics of making a chart and how to customize its design. In this section, I will talk about ‘event handlers’. If you are new to data visualization this might sound confusing, but if you are a JavaScript developer you will feel right at home as FusionCharts has made it easy to add event handlers to its charts.
3.a Handling Events
Event handling is a vast topic and deserves a separate post of its own. So instead of talking about it, I am going to give you a working example which will make further exploration easier for you.
Suppose you want to display the value of a donut slice whenever somebody clicks on it inside your chart. To achieve this you can use `dataPlotClick
` event. As the name suggests it is triggered whenever somebody clicks on a data plot. Data plot refers to the column in column chart, lines in a line chart, pie/doughnut slices in a pie/doughnut chart.
Here is how we do it:
This code will go after `Code:"events": { "dataPlotClick": function(eventObj, dataObj) { var a = document.getElementById('event-demo'); a.innerHTML = "You clicked on: " + dataObj.categoryLabel; } }chart
` options and `data
` array inside `dataSource
`. The event handler will receive `eventObj
` and `dataObj
` as it arguments:
`eventObj
` contains the details of the event like the type of event triggered, event id and other details associated with that event.
`dataObj
` is used to extract details associated with that particular data set on which click event was triggered. This object will contain the value, label etc. of the data set clicked. In our case we have used it to extract category label for the slice we have clicked to trigger the event.
We extract the label from the `dataObj
`( `dataObj.categoryLabel
`) and put it in an HTML element to display it on the page. To learn more about handling events you can check below pages:
Introduction to events in FusionCharts
API reference for events
I hope this was enough to give you a solid started with making charts in JavaScript. Feel free to post any questions in the comments section below.