Invert rows with columns on DataTable

41 views
Skip to first unread message

ALEEF02

unread,
Jan 29, 2019, 7:26:41 PM1/29/19
to Google Visualization API

Hi, I want to invert the rows and columns to make my chart look nicer. An image of reference is attached to what I want. What should I do?


Ray Thomas

unread,
Jan 30, 2019, 8:07:13 PM1/30/19
to Google Visualization API
As far as I know, the easiest way to do it is to the use the code from https://stackoverflow.com/questions/16949993/inverting-rows-and-columns-on-google-area-chart which in rturn comes from Bhuman's code at http://captaindanko.blogspot.com/2013/05/transpose-of-google-visualization-data.html

The Stackoverflow page also has a very compact version.

It's stable and works with everything I've tried it on. Here's an example of it in use - https://www.indstate.edu/business/metrics

Just click on any of the "Rotate graph data" checkboxes to see it work.

Original version:

  function transposeDataTable(dataTable) {
            //step 1: let us get what the columns would be
            var rows = [];//the row tip becomes the column header and the rest become
            for (var rowIdx=0; rowIdx < dataTable.getNumberOfRows(); rowIdx++) {
                var rowData = [];
                for( var colIdx = 0; colIdx < dataTable.getNumberOfColumns(); colIdx++) {
                    rowData.push(dataTable.getValue(rowIdx, colIdx));
                }
                rows.push( rowData);
            }
            var newTB = new google.visualization.DataTable();
            newTB.addColumn('string', dataTable.getColumnLabel(0));
            newTB.addRows(dataTable.getNumberOfColumns()-1);
            var colIdx = 1;
            for(var idx=0; idx < (dataTable.getNumberOfColumns() -1);idx++) {
                var colLabel = dataTable.getColumnLabel(colIdx);
                newTB.setValue(idx, 0, colLabel);
                colIdx++;
            }
            for (var i=0; i< rows.length; i++) {
                var rowData = rows[i];
                console.log(rowData[0]);
                newTB.addColumn('number',rowData[0]); //assuming the first one is always a header
                var localRowIdx = 0;

                for(var j=1; j< rowData.length; j++) {
                    newTB.setValue(localRowIdx, (i+1), rowData[j]);
                    localRowIdx++;
                }
            }
            return newTB;
      }

Compact version:
function transposeDateDataTable (dt) {
    var ndt = new google.visualization.DataTable;
    ndt.addColumn ('string',dt.getColumnLabel(0));
    for (var x=1; x<dt.getNumberOfColumns(); x++)
        ndt.addRow ([dt.getColumnLabel(x)]);
    for (var x=0; x<dt.getNumberOfRows(); x++) {
        ndt.addColumn ('number', dt.getValue(x,0).getDate());
        for (var y=1; y<dt.getNumberOfColumns(); y++)
            ndt.setValue (y-1, x+1, dt.getValue (x,y));
    }
    return ndt;
}
Reply all
Reply to author
Forward
0 new messages