Showing posts with label chart. Show all posts
Showing posts with label chart. 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.

Tuesday, January 17, 2012

How to create a histogram in OpenOffice.org

The recipe below has been tested in OpenOffice 3.0.1.
It is unclear (though expected) that it will work also in newer revisions.

The issue

Suppose you have a set of data, time data in my example, each representing when a certain event has happened. But rather having to digest the detail data you're only interested in high level information like how often did the measured event occur in an hour.

Here's the example data:
12:08
15:36
13:00
14:59
13:59
12:45
15:47
14:29
15:01
So you got a number of events at certain times, unsorted, uncounted.

Assume that these data are in column A in your spreadsheet, maybe labeled Time in the first row.

The goal

A histogram which depicts the frequency of the events per hour like this





The resulting histogram shows
3 events before 13:00
1 event between 13:00 and 14:00
2 events between 14:00 and 15:00
3 events after 15:00

How to get there


Identify the bins


In the example above identifying the bins for the histogram is rather easy: you pick full hours. It is also rather easy to find the minimum and maximum hours.
When your list of data is very long you might not easily see the minimum nor maximum nor might it be obvious how to set the bin intervals, a little trial and error is necessary to get there.

So looking at the data all events are later than 12:00 and none is beyond 16:00, therefore I'm choosing these bins:
13:00
14:00
15:00

I'm entering the bins into column B so that the spreadsheet looks like this now:

Calculate the frequencies


StarOffice contains a FREQUENCY function which takes two arrays as input and also returns an array of results (maybe something one has to get used to. The example will make it clear how to use it.
  • Enter Ticks (or any other describing string) into cell C1
  • Click into cell C2 and click on the functions icon.
  • Out of the list of functions select FREQUENCY
  • Enter your data range and your bin range into the resp. parameter fields so that it looks like this:

The spreadsheet should now look like this:

Create the chart

  • Mark columns B and C (click on B and drag towards C so that both are highlighted)
  • Insert -> Chart...
  • Step 1: leave the chart type at Column
  • Step 2: Data series in columns and First row as label should be ticked, additionally tick also First column as label
  • Step 3: simply click Next
  • Step 4: enter describing strings e.g. Histogram into Title, hours into X axis, frequency into Y axis

You're done.