Thursday, March 28, 2024

How to Create Beautiful Charts with jQuery

Tools of the Trade

Before we get started with the step-by-step process of creating charts using jQuery, let me list down the tools we will be needing:

Once you have above libraries with you, it’s time to start hacking!

This is what we are going to make in this tutorial: (see live CodePen demo here)

combination_chart

It is a combination chart with dual Y-axis. You can see it has both column and line charts in it. Combination charts allow you to plot multiple datasets on the same chart using different chart types together.

In a dual Y-axis combination chart, each axis has its own unit and magnitude, and each data series conforms to one of these axis. Try hovering over both data-plots to understand it better. (Data plot refers to the column in column chart, lines in a line chart, pie/doughnut slices in a pie/doughnut chart.)

I am going to use a 5-step framework similar to what I defined in my last article:

  • Step 1 – Preparing the data
  • Step 2 – Including required JavaScript files
  • Step 3 – Creating and selecting chart container
  • Step 4 – Inserting the chart
  • Step 5 – Customising the design

Once we get through above steps, I will share some advanced resources. Those resources will help you take your charts one step further.

Step 1 – Preparing the data

FusionCharts allows us to use both JSON and XML data formats. JSON (JavaScript Object Notation) has gradually become the default format for storing and exchanging data when it comes to modern day apps. If you are using any API, there’s a good chance that it provides data only in JSON. So I am going to use JSON data in my example.

JSON is made up of key-value pairs like this:

"song" : "teenage dream"

In above snippet:

  • “song” is the key. A key is always a string enclosed in quotation marks.
  • “teenage dream” is the value. A value can be a string, number, boolean expression, array, or object.

A key-value pair follows a specific syntax, with the key followed by a colon followed by the value. Key-value pairs are comma separated.

Once you understand JSON, you can easily prepare data for any chart. Suppose you want to make a pie-chart. Just head over to the chart attributes page and type ‘pie’. You will see complete JSON of a pie chart there. Just format your data in the same way it is defined in the data array and you are good to go.

For our example, it will be a little more complex than that since there are 2 different series. For this we need to form a dataset array. It will have two objects – one for each series (column and line). Inside each object, we will have a data array which will have data for individual series. I know this is getting a bit complex, and it will make more sense if you have a look at it (or you can follow along with project code as well):

"dataset": [{

    //first series
    "seriesName": "Sales",  
    "data": [{
        "value": "32044.38"
        }, {
        "value": "58828.83"
        },
        //more values
        ..]
    }, {

    //second series
    "seriesName": "Units Sold",
    ...
}]

Hope it makes sense now!

Step 2 – Including JavaScript files

Next step is to start setting up the page by including required JavaScript files through HTML <script> tag. First one is jQuery. Include it either via CDN or your local development folder. Next is FusionCharts’ core JavaScript charts library, and final is their jQuery charts plugin.

Here is how how we include the required files:

<head>

    <!-- jQuery via CDN or using local link -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.12.0.min.js"></script>

    <!-- FusionCharts Core JavaScript File-->
    <script type="text/javascript" src="path/to/fusioncharts.js"></script>
    <script type="text/javascript" src="path/to/fusioncharts.charts.js"></script>

    <!-- FusionCharts' jQuery Plugin -->
    <script type="text/javascript" src="path/to/jquery-plugin.js"></script>

</head>

Step 3 – Creating and Selecting Chart Container

We will use an HTML <div> element as our chart container:

<body>
    <div id="chart-container">An awesome chart is on its way!</div>
</body>

We will select our container using standard jQuery $ selector:

$('#chart-container')

Note: you will need separate <div> container for every chart you include in your page.

Step 4 – Inserting the chart using insertFusionCharts method

We will now insert the chart using the insertFusionCharts method provided by the jQuery plugin.

Here is how we do it:

(function() {
  $("#chart-container").insertFusionCharts({
    type: "mscombidy2d",
    renderAt: "chart-container",
    width: "100%",
    height: "500",
    dataFormat: "json",
    dataSource: {

      "chart": {
        "caption": "Acme Inc's Sales Analysis",
        // More chart cosmetics 
      },

      "data": [
        {"label":"Food","value":"28504"},
        {"label":"Apparels","value":"14633"},
        // More chart cosmetics
      ]
    }
  });
  //end of FusionCharts instance
}());

Let’s look at some of the configuration options we have defined above:

  • type: defines the chart type we are going to plot – mscombiy2d in this example.
  • height: height of the chart in pixels (500px).
  • width: width of the chart (100%).
  • dataFormat: format in which data is being fed. JSON in our case.
  • chart: defines properties like caption, label etc. Discussed in more detail in the next step.
  • data: the data for constructing the chart.

Step 5 – Customising the Design

This is my favorite part of the process as I can be as creative as I want. There are literally hundreds of little things you can play around with to make your chart look perfect. Let me give you few examples:

  • bgColor and canvasBgColor: These attributes let you set the background color for the chart and canvas. You can set any hex color code as the value of these attributes.
  • baseFont: you can control the font being used on your chart via this attribute. It not only allows you to use standard fonts, but you can use any font under the sun. For this example I have used ‘Roboto Slab’ via Google Fonts. To use a custom font, just include the font in the HTML head section.
  • renderAs – this attribute goes inside dataset array and lets you define the secondary plot type – line or area.

There is a lot more you can do with customizing design. If you are interested in learning more, then check out the mega list of attributes here.

More Resources

If you don’t like working with vanilla JavaScript, then I hope you found this jQuery charts tutorial useful. We built a simple chart today, but you can do a lot more crazy stuff:

  • Use data present in HTML tables as input to your chart: Suppose you have an HTML table on your page and you want to visualize that table’s data. You can easily render a chart using pre built ‘convertToFusionCharts’ method.
  • Use events: Suppose you want to display additional information on your HTML page if somebody clicks on the chart. You can use dataPlotClick event to achieve this. There’s a lot more that is possible and you can explore more events here.
  • Do more than just jQuery: Don’t use jQuery? You can AngularJS charts or PHP charts plugin if any of those are part of your tech stack. Both the above pages contain a short guide to help you get started quickly.

I hope you enjoyed this tutorial! Feel free to post any comment below or catch me on Twitter @LalwaniVikas if you have any questions. Always happy to help!

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured