News

Generate interactive graphs with the Rickshaw library

Graphs are perfect for illustrating interesting trends in data and help viewers absorb information much quicker. Use the Rickshaw library to build gorgeous-looking graphs

javascriptlogo

The modern web is all about communicating information quickly and easily. In the past, creating a graph to help illustrate data would have involved using a spreadsheet application in order to output a chart as a graphic. Fortunately for us, however, times have moved on.

With the power of SVG, it’s now possible to generate high-quality graphics procedurally at the time of a page render, making it relatively trivial to plot data points. It’s still not for the faint of heart to code directly in SVG, though, and that’s where the Rickshaw library is incredibly useful. By passing in a dataset and defining a small set of parameters, you can generate gorgeous, interactive charts that add to the user experience.

In this tutorial we’ll set up a simple chart using Rickshaw and make it respond to user input. By the time you have finished, you’ll have everything you need to generate your own charts and use them on your site.

DOWNLOAD TUTORIAL FILES

Create the HTML

All our code is going to happen inside a JavaScript document, but we still need some basic HTML elements to work with – so start off by creating a chart container <div>, and within it place a separate <div> for each of the chart, the y-axis, the legend and a form to alter our final chart. You can find our starting HTML on the resource disc.

001 <!doctype html>        
002 <html>                            
003    <head>
004        <meta charset=”UTF-8”>
005        <title>Using the Rickshaw Library to     create graphs</title>
006        <link type=”text/css” rel=”stylesheet”     href=”styles/screen.css” />
007    </head>
008    <body>
009        <div id=”header”>
010            <h1>USING THE RICKSHAW LIBRARY TO     GENERATE GRAPHS</h1>
011        </div>
012        <div id=”container”>
013            <div id=”chart_container”>
014                <div id=”y_axis”></div>
015                <div id=”chart”></div>
016                <div id=”legend”></div>
017                <form id=”offset_form”         class=”toggler”>
018                    <p>Display chart as:</p>    
019                    <input type=”radio” name=”offset”  id=”lines” value=”lines” checked=”checked” />
020                    <label class=”lines”         for=”lines”>lines</label><br>
021                    <input type=”radio” name=”offset” id=”bar” value=”zero” />
022                    <label class=”stack”         for=”stack”>bar</label>
023                </form>
024            </div>
025            <h2>Taxation as percentage of GDP     1965 - 1976</h2>
026            <p style=”text-indent:40px;”>Source:     OECD (<a href=”http://www.oecd.org/ctp/    taxpolicyanalysis/revenuestatisticstaxratio    schangesbetween1965and20102012edition.htm”     title=”View source”>http://www.oecd.org/ctp/    taxpolicyanalysis/revenuestatisticstaxratiosch    angesbetween1965and20102012edition.htm</a>)</    p>    
027        </div>    
028        <script src=”scripts/main.js”></script>
029    </body>
030 </html>

Download Rickshaw

We’re going to be using the open source Rickshaw library which was developed on top of D3 by ShutterStock. You can grab the code from the GitHub page at github.com/shutterstock/rickshaw and view a getting-started guide at code.shutterstock.com/rickshaw. Once you have downloaded the files, copy the scripts and styles into your site folder, and include them in your page as shown in bold.

001 <!doctype html>
002 <html>
003    <head>
004        <meta charset=”UTF-8”>
005        <title>Using the Rickshaw Library to     create graphs</title>
006        <link type=”text/css” rel=”stylesheet”     href=”styles/rickshaw.min.css” />
007        <link type=”text/css” rel=”stylesheet”     href=”styles/screen.css” />    
008        <script src=”scripts/d3.min.js”></script>
009        <script src=”scripts/d3.layout.min.js”></script>
010        <script src=”scripts/rickshaw.min.js”></    script>
011    </head>
012    <body>
013        <div id=”header”>
014            <h1>USING THE RICKSHAW LIBRARY TO     GENERATE GRAPHS</h1>
015        </div>
016        <div id=”container”>
017            <div id=”chart_container”>
018                <div id=”y_axis”></div>
019                <div id=”chart”></div>
020                <div id=”legend”></div>
021                <form id=”offset_form”         class=”toggler”>
022                    <p>Display chart as:</p>
023                    <input type=”radio” name=”offset”  id=”lines” value=”lines” checked=”checked” />
024                    <label class=”lines”         for=”lines”>lines</label><br>
025                    <input type=”radio” name=”offset” id=”bar” value=”zero” />
026                    <label class=”stack”         for=”stack”>bar</label>
027                </form>
028            </div>
029            <h2>Taxation as percentage of GDP 1965  - 1976</h2>
030            <p style=”text-indent:40px;”>Source:     OECD (<a href=”http://www.oecd.org/ctp/    taxpolicyanalysis/revenuestatisticstaxratio    schangesbetween1965and20102012edition.htm”     title=”View source”>http://www.oecd.org/ctp/    taxpolicyanalysis/revenuestatisticstaxratioscha    ngesbetween1965and20102012edition.htm</a>)</p>
031        </div>
032        <script src=”scripts/main.js”></script>
033    </body>
034 </html>

Add style

We’ll need some basic styles for our page, to help define how the chart will look (although this is also handled by the script) – and the stuff around the chart. Test your page as you create these styles to make sure you’re happy with the overall look, but keep in mind the chart will be configured later!

001 body {
002        background:        #efefef;
003        margin:        0;
004        padding:        0;        
005        font-family:     Helvetica, Arial,     sans-serif;
006        font-size:        62.5%;
007        color:        #4a4a4a;    
008    }
001    #header {
002        position:        relative;
003        width:        920px;
004        margin:        auto;
005        padding:        20px;
006        background:        #fff;
007        box-shadow:        0px 0px 10px #999;    
008        border:        1px solid #999;
009        margin-top:        20px;
010        border-radius:     10px;        011    }
001    #container {
002        position:        relative;
003        width:        920px;
004        margin:        auto;
005        padding:        20px;
006        background:        #fff;
007        box-shadow:        0px 0px 10px #999;    
008        border:        1px solid #999;
009        margin-top:        20px;
010        border-radius:     10px;
011    }
001    h1, h2 {
002        font-weight:    normal;
003        text-transform:    uppercase;
004        margin:        0;
005        padding:        0;
006    }
001    h1 {
002        font-size:        2.5em;
003    }
001    h2 {
002        font-size:        2em;
003        text-indent:    40px;
004    }
001    #chart_container {
002            display:     inline-block;
003    }
001    #chart {
002            float:     left;
003    }
001    #legend {
002            float:     left;
003            margin-left: 15px;
004    }
001    #offset_form {
002            float:     left;
003            margin:     2em 0 0 15px;
004            font-size: 13px;
005    }
001    #y_axis {
002            float:     left;
003            width:     40px;
004    }

Test a chart

We’ll start off by generating a simple test chart to check that everything is installed and working properly. Create a new JavaScript document and save it as main.js. You’ll notice the call to it has already been set up in our HTML document at the bottom, just before the </body> tag. Save and test!

001 var graph = new Rickshaw.Graph({
002    element: document.querySelector(“#chart”),
003    width: 720,
004    height: 320,
005    renderer: ‘area’,
006    series: [{ 
007    name: “test”,
008        data:[
009            {x:1,y:10},
010            {x:2,y:5},
011            {x:3,y:7}
012        ],
013        color: “rgb(255,0,0)”
014    }]
015 });
016                
017 graph.render();

Breaking it down

All being well, you should now be viewing a red area chart within your page. Let’s take a quick look at how it all works. Firstly, we generate a new graph object with the code var graph = new Rickshaw.graph(). Within the parenthesis, we pass in a set of options – the width, height, HTML element and data series to use. Finally, we use the render method to generate the completed chart.

Get some real data

We need some real data to use in our chart. You can choose any dataset you like, but we grabbed some tax versus GDP figures from the OECD (which is an interesting illustration of the differences between countries!). We’ve included the spreadsheet from the OECD site on the cover disc, or you can grab it directly from www.oecd.org/ctp/taxpolicyanalysis/.

Convert the data

We need to convert the data into something usable by Rickshaw. This means plotting each data point inside the data object, just as we did in step 4 with the dummy data. Start by selecting the range of data you’d like to cover, then copy each set into your JavaScript file accordingly.

Convert the dates

If you test your page at this point, you’ll see it’s quite a mess. This is because although we’ve got the data in place, the chart renders in a horrible mess of overlapping colours. We need to convert each year into a UNIX timestamp, which will allow us to use a built-in method to plot the X axis. Convert each year into UNIX time, or copy our code from the resource disc.

Generate the axis labels

Our data is meaningless without chart axis labels in place to help us understand it. We can install these by creating new chart objects with the Rickshaw library. The X axis will generate the year automatically using our UNIX timestamps. Add the code shown before the render() method is called.

001 var x_axis = new Rickshaw.Graph.Axis.Time( { graph: graph } );
002            
003 var y_axis = new Rickshaw.Graph.Axis.Y( {
004    graph: graph,
005    orientation: ‘left’,    
006    tickFormat: Rickshaw.Fixtures.Number.    formatKMBT,
007    element: document.getElementById(‘y_axis’),
008 });

Change the chart type


You’ll notice that we’ve got an area chart currently, and the different data sets stack up to provide a false reading of the total amount of taxation. We need to choose a more appropriate chart type for our data set. We can do this easily by changing the setting for the renderer in our chart code. Do that now, setting the renderer to ‘line’ instead of ‘area’.

001 var graph = new Rickshaw.Graph({    
002                    element: document.        querySelector(“#chart”),
003                    width: 720,
004                    height: 320,
005                    renderer: ‘line’,
006                    series: [
007                            {
008                                    name: “Japan”,
009                                    data: [ { x:     -157766400, y: 17.8 },...

Add the legend

Now that we’ve got an appropriate scale, and the data showing up correctly, we need to know what each line refers to! We’ve already got an HTML element ready to become the legend, so set this up by adding a legend object using the code shown. You should be starting to get a sense of how the Rickshaw library works by now!

001            var legend = new Rickshaw.Graph.    Legend( {
002                    element: document.        querySelector(‘#legend’),
003                    graph: graph
004            });

Add some interactivity


One of the benefits of using an interactive runtime charting system is that we can make it respond to user input. We will enable the user to switch chart types shortly, but first there are some built-in methods that provide useful feedback as the visitor interacts with your chart. Try the highlighter option by adding the code shown.

001 var highlighter = new Rickshaw.Graph.
 Behavior.  Series.Highlight({
002 graph: graph,
003       legend: legend
004    });

More interaction!

The code we added in the previous step makes the legend interactive – try rolling over it with your mouse! In the same way, we can add a nice interactive data point pop-up so the user can see individual data values on the chart itself. Add the code shown to put
this in place.

001            var hoverDetail = new Rickshaw.Graph.   HoverDetail( {
002                   graph: graph
003            });

Changing charts

The final piece we need to put in place is to allow the user to change the chart type. We’ve already got a form waiting to be used for exactly this purpose, so we need to start by grabbing the form DOM element in our JavaScript and assigning an ‘on change’ event listener to fire each time the radio buttons are updated by the user.

001            var offsetForm = document.        
002 getElementById(‘offset_form’);
003            
004            offsetForm.addEventListener(‘change’,  function(e) {
005            
006            }

Get the value

When the value of the selected radio button changes, the function we’ve just created will be called. Inside the function we need to check for the value and take action appropriately. To keep it simple, we’ve limited the options to either a line chart or a pie chart, so start off by checking which option is selected.

001            var offsetForm = document.        getElementById(‘offset_form’);
002            
 
003            offsetForm.addEventListener(‘change’,   function(e) {
004                    // find out what the selected      value is
005                    var offsetMode = e.target.value;
006
007                    if (offsetMode == ‘lines’) {
008                        // The line option was chosen
009                    } else {
010                        // It wasn’t the line option,   so it must be the bar chart option
011                    }       
012            }

Set the type

Now all we need to do is to fill in the appropriate chart type using the setRenderer method. If we’ve got a selected value of ‘line’, we will set the renderer type to line, otherwise we’ll set it to bar. Note that we’ve also used an extra option when the chart type is set to bar – unstack prevents the bars being loaded one on top of the other. This would also work with the area chart we started off with.

001            var offsetForm = document.             getElementById(‘offset_form’);
002            
003            offsetForm.addEventListener(‘change’,  function(e) {
004                    // find out what the selected      value is
005                    var offsetMode = e.target.value;
006            
007                    if (offsetMode == ‘lines’) {
008                        // The line option was chosen
009                        graph.setRenderer(‘line’);
010                    } else {
011                        // It wasn’t the line option,   so it must be the bar chart option
012                        graph.setRenderer(‘bar’);
013                        graph.renderer.unstack = true;
014                    }       
015            }

Re-render!

All the code we’ve just added doesn’t do anything until we tell the chart to re-render. This is a simple matter of calling the same method we used in step 4 – graph.render(). Add that to the bottom of the change listener function, and test in your browser to make sure everything works as it should.

001 graph.render(); 
×