Thursday, April 11, 2013

Resizable Google Chart

To resize a Google chart (pie chart, area chart, geo chart ...) is a matter of a few lines of code after refactoring the given example in the Google Charts Gallery. The keyword is: window resize.

Just keep your data in a javascript variable and put the Google Chart code in a function to be called in each onResize event. That way the chart will be redraw to fit in the new size of the chart div, and it will look like it is resizing / scaling.

Note that you may want to set a min/max width/height for the size of the chart (css on the div can do the job just fine).

Performance? Just fine. Unless you have large data and many details to draw, then it may be a headache to draw from the beginning at each resize (you can limit the chart resize frequency with javascript by a delay or timer).

Here is a complete example:

    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
    window.onresize = function(){

    window.onload = function(){

    var data_array = [
                      ['Year', 'Sales', 'Expenses'],
                      ['2004',  1000,      400],
                      ['2005',  1170,      460],
                      ['2006',  660,       1120],
                      ['2007',  1030,      540]
    startDrawingChart = function(){
        google.load("visualization", "1", {packages:["corechart"],callback: drawChart});

        function drawChart() {
            var data = google.visualization.arrayToDataTable(data_array);

            var options = {
              title: 'Company Performance',
              hAxis: {title: 'Year',  titleTextStyle: {color: 'red'}}

            var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
            chart.draw(data, options);
    <div id="chart_div"></div>