Google Charts: Invert a DataTable


The following javascript code creates an inverted Google DataTable where the old x-axis gets the new y-axis and vice versa. It’s quite straight forward but maybe someone else or the future me can save some time. If I missed the ready-to-use api method for that please leave a comment.

http://jsfiddle.net/QtynG/

input:
foo	NumberCol1 NumberCol2
1 	val  		val
2 	val 		val
3	val		val
4	val		val
5	val		val

output:
caption         1    2   3   4   5
NumberCol1     val  val val val val
NumberCol2     val  val val val val
function invertTable(dt, caption) {
	   
	    var invertedTable = new google.visualization.DataTable();

            var colCount = dt.getNumberOfRows();
            var rowCount = dt.getNumberOfColumns();

            //create caption column
            invertedTable.addColumn('string', caption);

            //create value columns
            for (var i = 1; i <= colCount; i++) {
                invertedTable.addColumn('number', dt.getValue(i-1,0));
            }

            //insert data rows
            for (var i = 1; i < rowCount; i++) {
                invertedTable.addRow();
                invertedTable.setValue(i - 1, 0, dt.getColumnLabel(i));

                for (var j = 1; j <= colCount; j++) {
                    invertedTable.setValue(i - 1, j, dt.getValue(j - 1, i));
                }
            }
	    return invertedTable;
}

,

  1. #1 von MJ am November 6, 2012 - 10:01 pm

    Excellent, just what I was looking for! Thank you!

(wird nicht veröffentlicht)