Showing posts with label stacked histogram. Show all posts
Showing posts with label stacked histogram. Show all posts

Thursday, January 24, 2013

Stacked column charts with Google charts (compared to gnuplot)

Some time ago I had written about stacked histograms in gnuplot.

Today I wanted to see how to achieve the same result with Google charts.

For the purpose of this first exercise I was using the client side only and didn't worry about where the data should or could come from (in gnuplot data came from a file, naturally) but I put them directly into the JavaScript code.

So first take a look at the result.

As you can see the charts are pretty similar to gnuplot. There is currently one caveat in Google charts where you can't have multiline titles so it's displayed as one line.


So here is the JavaScript code.
The code is a slight modification of the Google charts column chart example and of course the calculation of the percentages for the second chart is the only piece where some real additional work is required.
I left all settings at their defaults (like colours, fonts etc.) except for the obvious y-axis title and height, chart title, thickness of chart border (in order to get a nice box) and the most important isStacked setting.

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("visualization", "1", {packages:["corechart"]});
 
  var dataSet = [
        ['year', 'foo', 'bar', 'rest'],
        ['1900', 20, 10, 20],
        ['2000', 20, 30, 10],
        ['2100', 20, 10, 10]
        ];

  // The first chart

  google.setOnLoadCallback(drawChart1); 
  function drawChart1() {
    var data = google.visualization.arrayToDataTable( dataSet );

    var options = {
      title: 'Stacked histogram\nTotals',
      vAxis: {title: 'total', maxValue: 100},  // sets the maximum value
      backgroundColor: {strokeWidth: 2 },  // to draw a nice box all around the chart
      isStacked: 'true'                    //  = rowstacked in gnuplot
    };

    var chart = new google.visualization.ColumnChart(document.getElementById('chart_div1'));
    chart.draw(data, options);
  }

  // The second chart

  var dataSet2    = dataSet;
  google.setOnLoadCallback(drawChart2);
  function drawChart2() {
    // Calculate the percentages
    var sum = new Array();
    for(row=1; row<dataSet.length; row++) {
      sum[row]        = 0;
      for(col=1; col<dataSet[row].length; col++) {
        sum[row]        += dataSet[row][col];
      }
      for(col=1; col<dataSet[row].length; col++) {
        dataSet2[row][col]      = 100*dataSet[row][col]/sum[row];
      }
    }

    var data = google.visualization.arrayToDataTable(dataSet2);

    var options = {
      title: 'Stacked histogram\n% Totals',
      vAxis: {title: 'total', maxValue: 100},  // sets the maximum value
      backgroundColor: {strokeWidth: 2 },  // to draw a nice box all around the chart
      isStacked: 'true'                    //  = rowstacked in gnuplot
    };

    var chart = new   google.visualization.ColumnChart(document.getElementById('chart_div2'));
    chart.draw(data, options);
  }
</script>

<div style="display: table;">
  <div style="display: table-row">
    <div id="chart_div1" style="width: 300px; height: 300px; display: table-cell;"></div>
    <div id="chart_div2" style="width: 300px; height: 300px; display: table-cell;"></div>
  </div>
</div>

Not having worked with Google charts before I did develop this in a couple of hours which shows that Google charts work well and can be learned pretty fast given that you have an idea about charts and its terminology.

Why Google termed their axes horizontal and vertical rather than using the mathematical standards x and y is the secret of their product team though.

There is some discussion whether and how to use Google charts (data privacy etc.) since it seems that data are sent to and processed by Google servers (or servers of other chart type providers) but that is beyond the scope of this blog.

The next step will be to look into the server side piece of Google charts i.e. writing a data provider.

Thursday, December 16, 2010

Gnuplot - Stacked Histograms

Since gnuplot cannot generate pie charts an alternative are stacked histograms.
In fact stacked histograms are even better in my mind since one can put the histograms next to each other and this allows better comparability than looking at a number of pie charts.
A single pie chart might make sense but in reality it's more often about how does the current chart compare to a previous one.

Here I present an easy example how to generate stacked histograms (available in gnuplot since version 4.1).
For fancier examples go to the Gnuplot histogram demos.

Consider this example (call it stackedhisto.dat):
year foo bar rest
1900 20 10 20
2000 20 30 10
2100 20 10 10
We have 1 row with header information and 3 rows of data.
For each year we have measured 3 values foo, bar and rest which we want to show in graphs in two different ways.

The first graph shows the stacked histogram with the nominal values of the data i.e. the height of the first bar is 50 (=20+10+20).

The second graph shows the percentage distribution i.e. all values are scaled to 100.
The same nominal '20' in graph 1 leads to percentages 40, 33.3 and 50 in graph 2.
One box of this type of graph is often depicted as a pie chart so rather than comparing 3 pie charts (one for each year) here we have 3 boxes in one graph, much easier to compare.

The gnuplot code

#
# Stacked histograms
#
set term png size 300,300
set output 'stackedhisto.png'
set title "Stacked histogram\nTotals"

# Where to put the legend
# and what it should contain
set key invert reverse Left outside
set key autotitle columnheader

set yrange [0:100]
set ylabel "total"

# Define plot style 'stacked histogram'
# with additional settings
set style data histogram
set style histogram rowstacked
set style fill solid border -1
set boxwidth 0.75

# We are plotting columns 2, 3 and 4 as y-values,
# the x-ticks are coming from column 1
plot 'stackedhisto.dat' using 2:xtic(1) \
    ,'' using 3 \
    ,'' using 4


# New graph
# We keep the settings from above except:
set output 'stackedhisto1.png'
set title "Stacked histogram\n% totals"
set ylabel "% of total"

# We are plotting columns 2, 3 and 4 as y-values,
# the x-ticks are coming from column 1
# Additionally to the graph above we need to specify
# the titles via 't 2' aso.
plot 'stackedhisto.dat' using (100*$2/($2+$3+$4)):xtic(1) t 2\
    ,'' using (100*$3/($2+$3+$4)) t 3\
    ,'' using (100*$4/($2+$3+$4)) t 4

The generated graphs