m1gin

#googlecharts #charts #columnchart #piechart #javascript


Get Columns and Rows Count in table

  • data.getNumberOfColumns();
  • data.getNumberOfRows();

Example:

 <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script>

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawColumnChart);

function drawColumnChart(){
var colchartdata = [ ["opt 1", 5], ["opt 2", 8], ["opt 3", 33] ];  

var data = new google.visualization.DataTable();
data.addColumn('string', 'Vote');
data.addColumn('number', 'VoteCount'); 

//data.addRows(2);    
data.addRows(colchartdata);

//add a new style column
data.addColumn({ type: 'string', role: 'style' });

//set style column for the rows;
data.setValue(0,2, "color:#f00");
data.setValue(1,2, "color:#ff0");

var view = new google.visualization.DataView(data);
//view.setColumns([0, 1, { calc: "stringify", sourceColumn: 1, type: "string", role: "annotation" }, 2]);       

var options = {
  title: "Google chart",
  width: 600,
  height: 400,
  bar: {groupWidth: "95%"},
  legend: { position: "none" },   
};
        
var chart = new google.visualization.ColumnChart(document.getElementById("divcolchart"));              
chart.draw(view, options);


//change bar color and get values when clicking on it.

     google.visualization.events.addListener(chart, 'select', function () {
        var selection = chart.getSelection();
        if (selection.length) {
            var row = selection[0].row;
            var votecount= data.getValue(row, 2);
            document.querySelector('#divpiechart').innerHTML = "row: " + row + ", votecount: " + votecount;
            
            var view = new google.visualization.DataView(data);
            view.setColumns([0, 1, 2, {
                type: 'string',
                role: 'style',
                calc: function (dt, i) {
                    return (i == row) ? 'stroke-color:#f00; stroke-width:4; color:' + colors[i] : 'color:' + colors[i];
                }
            } ]);
            
            chart.draw(view, options);
        }
    });


}

</script>

Add to: