Get started in learning to code.
Start Learning

Rohit Boggarapu, a software engineer at Adobe (and one of our favorite guest authors!), returns today for another great teaching post.

In my last article, I listed out 12 best charting libraries for web developers. And today, I am going use one of those libraries to plot something interesting—the time taken by Berkshire Hathaway, Apple, Microsoft, Amazon, Google, and Facebook to reach $300bn market capitalization (value).

I will use FusionCharts JavaScript charts library for this project as it offers a huge library of 90+ charts, is compatible with every browser, and is easy to work with. I will start by making a simple chart and then proceed to add advanced features like annotations and event handlers to it.

This is what our project will look like at the end:

JavaScript Charts

Source: this tweet by Chamath Palihapitiya. Check out the live version of the above chart here, and access the project’s GitHub repo here. Now, let’s get started!

Making Your First Chart: 2 Step Process

I will describe only the necessary steps in this post. For detailed instructions, you can go through the code as explained in the above linked GitHub repo.

Step 1: Including Scripts and Creating Chart Container

Every web app has some dependencies which need to be included through HTML <script> tags. Our project is dependent on only following 2 files:

  • fusioncharts.js
  • fusioncharts.charts.js

You will find both the files in the zip package which you can download from here. And here is how we include them inside <head> section of our HTML page:

<script type="text/javascript" src="js/fusioncharts.js"></script>
<script type="text/javascript" src="js/fusioncharts.charts.js"></script>

To house our chart we need an HTML <div> container. Here’s how we include it inside <body> section of our HTML page:

<div id="top-companies">A beautiful chart is on its way.</div>

Step 2: Creating Chart Object and Rendering the Chart

Quick note: to make steps after this easier to understand I have separated the JavaScript for the project in a separate file called udacity-chart.js (see here).

Once we have our setup ready, we need to declare the chart object and data array using FusionCharts constructor. Here is how we do it:

var unicorns = new FusionCharts({
  type: 'column2d',
  renderAt: 'top-companies',
  width: '100%',
  height: '500',
  dataFormat: 'json',
  dataSource: {
    "chart": {
      "caption": "Time to $300bn Market Cap",
      "yAxisName": "# Years",
      // more chart customizations
    },

    "data": [{
        "label": "Berkshire Hathaway",
        "value": "49",
      }, {
        "label": "Apple",
        "value": "35"
      }, // more data 
    ]

  }
});
unicorns.render();

Some explanation for above code:

  • type, width and height are defining type of chart we are plotting (column 2d), width of the chart and its height. 100% width means the chart will take up full container width.
  • renderAt is telling the chart where to render (id of the div, ‘top-companies’ in our case)
  • dataFormat defines the format in which we will feed the data to the chart – ‘json’ in our case.
  • dataSource object contains the content of the chart. Here is what goes inside it:
    • Chart object: this contains chart configuration options like caption, axis names, palette colors, background colors etc. These options are called ‘chart attributes’ and there is a lot you can do through them to make your chart stand out. I am not going to cover many here as these are self explanatory. But if you are making a chart, you can bookmark this page for reference(just search for a chart type to see applicable chart attributes).
    • Data array: FusionCharts accepts chart data as array of objects containing label and value pairs. Label in our case will be be the name of the column (Apple, Google etc.) and value is the number we want to plot corresponding to it (no. of years it took to reach $300bn market capitalization).
  • In the end we call the render method to render the chart inside our container.

I hope you got a working chart after following these instructions. If not, check where you went wrong and rectify the mistake before proceeding to the next section.

Advanced Customizations

What you’ve created so far is a good chart, but it can become much better. In this section, I will cover two advanced features – annotations and event handlers – that will take your chart to the next level.

Adding Images Through Annotations

Annotations let you add custom text, shapes or images to your chart. In our case we are going to add company logos at the top of corresponding columns. Below I have described the process of adding images via annotations, and to learn about what else can be done please refer to this documentation page.

Process of adding annotations is very similar to the process we followed in above steps. Just like chart object and data array, annotations will go inside dataSource. Here is what the syntax looks like: (explanation after code snippet)

"annotations": {
  "groups": [{
    "id": "logo-images",
    "xScale": "30",
    "yScale": "30",
    "showBelow": "0",
    "items": [{
        "id": "bh-icon",
        "type": "image",
        "url": "img/bh.jpg",
        "x": "$dataset.0.set.0.STARTX",
        "y": "$dataset.0.set.0.STARTY - 100"
      }, // more items
    ]
  }]
}

In the above code:

  • We are grouping our annotations inside a group with id ‘logo-images’. Having a unique id will allow us to manipulate all the annotations inside the group together.
  • xScale and yScale are defining the scale of images. Value of 30 means images will be scaled to 30% of their original size.
  • Zero inside showBelow is telling the images to sit above the columns. A value of 1 would have put the images at the bottom of the columns.
  • items array contains objects containing details for each individual image:
    • id is the unique id for that image. It’s optional in our case as we are not going to do anything with it.
    • type defines the type of annotation (text, image etc.).
    • url is the location of the image. All our images are inside img folder.
    • For defining coordinates of the image we are making use of macros. $dataset.0 will select the first data set. It is not very useful here as we have only one data set, and it comes more handy when you are plotting multiple series. So all our columns will be referenced by $dataset.0.set.0.STARTX will point us to the starting position’s x coordinate of first column. It might sound confusing at first, but will be easier once you get used to it. If this went completely above your head, take a minute to read more about positioning using macros here.

Adding Event Handlers

If you hover over any column of our chart, you will notice that values inside the table below the chart change depending on your mouse position. For example, if your cursor is over Apple’s column, you will see data related to Apple.

We are doing this via an event handler provided by FusionCharts called dataPlotRollOver. It lets us control the chart’s behavior when somebody hovers over a data plot. Data plot is a fancy term to refer to columns in a column chart, lines in a line chart, or pie slices in a pie chart.

First we need to create an HTML structure using <div> elements for the data we want to show for each company. Here is the HTML that I have used:

<div class="details">
  <div id="company">Hover over the columns above.</div>
  <div class="row">
    <div id="year" class="cell left"></div>
    <div id="marketCap" class="cell right"></div>
  </div>
  <div class="row">
    <div id="revenue" class="cell left"></div>
    <div id="hq" class="cell right"></div>
  </div>
</div>

Once we have our HTML ready, we move to JavaScript:

var companyData = [{
    foundingYear: 1955,
    revenue: 210.82,
    marketCap: 350.59,
    hq: 'Nebraska'
  }, // data for more companies
]

dataSource: {
  "chart": {}, // chart configuration options - discussed above
  "annotations": {}, // annotations - discussed above
  "data": {}, // chart data - discussed above
  "events": {
    "dataPlotRollOver": function(eventObj, dataObj) {
      document.getElementById('company').innerHTML = dataObj.categoryLabel;
      document.getElementById('year').innerHTML = "Founded in " + companyData[dataObj.index].foundingYear + ".";
      // fetching and displaying more data
    }
  }
}

As you can see above, events is defined in the same way as chart object, annotations and data array.  Event handler receives eventObjdataObj as its arguments:

  • eventObj contains details related to the event – type of event, event id etc.
  • dataObj contains details about the particular data plot on which the event occurred. In our case it will have label, value etc. of the column that we hover over.

We extract and pass the label of a column using dataObj.categoryLabel. dataObj.index returns the index of a particular column. We use it to extract related values stored inside our array of objects (companyData).

To explore more on events, please visit this API reference page. It has good descriptions and a working JSFiddle demo for every event.

More Resources

When you try to make a chart on your own you will find the resources below helpful:

  • Documentation: if you get stuck anywhere, documentation is the first place you should look. Here are handy documentation links for chart attributes, annotations and events.
  • Live examples: another advantage of using FusionCharts is that it offers an extensive gallery of live examples with full source-code. You don’t need to start from scratch every time you need to make a chart. Just fork an existing fiddle and then customize it to your wish.

Have any questions? Catch me on Twitter – I’ll be happy to help! ~Rohit Boggarapu

Christopher Watkins
Christopher Watkins
Christopher Watkins is Senior Writer and Chief Words Officer at Udacity. He types on a MacBook or iPad by day, and either an Underwood, Remington, or Royal by night. He carries a Moleskine everywhere.