Multiple data sets with regular charts

Sometimes you find yourself in a situation where you need one chart to display several sets of data. You also need your user to be able to switch them dynamically, without reloading the page. However, the charts do not support this functionality out of the box.

Fortunately it's very easy to implement using some custom JavaScript Code.

I'll be using column chart as an example, however the process is identical for all serial charts. (line, bar, radar, polar, pie).

First of all we define our data sets and put them into one big array:

var chartData = [
    // Data set #1
    [
        { country: "Czech Republic", litres: 156.90},
        { country: "Ireland", litres: 131.10},
        { country: "Germany", litres: 115.80},
        { country: "Australia", litres: 109.90},
        { country: "Austria", litres: 108.30},
        { country: "UK", litres: 99.00}
    ],
    // Data set #2
    [
        { country: "Czech Republic", litres: 101.20},
        { country: "Ireland", litres: 141.20},
        { country: "Germany", litres: 91.80},
        { country: "Australia", litres: 101.90},
        { country: "Austria", litres: 125.30},
        { country: "UK", litres: 101.50}
    ]
];

Let's use the first data set as default dataProvider for our initial chart:

chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData[0];

Now let's add some control in HTML that will serve as data set switcher:

<div id="selector">Select a dataset:
    <label><input type="radio" value="0" name="dataset" checked="checked" onclick="selectDataset(0);"> Data set #1</label>
    <label><input type="radio" value="1" name="dataset" onclick="selectDataset(1);"> Data set #2</label>
</div>

And finally, we should add the function that will handle the actual switch of the data set:

function selectDataset(d) {
    chart.dataProvider = chartData[d];
    chart.validateData();
    chart.animateAgain();
}

The above function is pretty self-explanatory. First we update chart's dataProvider with different data set. Then call chart.validateData() so the chart takes in the new data. And finally call chart.animateAgain() so the chart shows animation for a good measure.

Here's the above example in action.