Skip to content
Advertisement

Make google chart responsive

Im using google charts in a project but im having a hard time to make them responsive.

Iǘe seen other examples on responsive charts but I cant seem to get it to work in my case. All my charts gets rendered and after that their sizes do not change.

If someone can make this chart responsive id appreciate it. Thank you:

function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Year');
    data.addColumn('number', 'Revenue');
    data.addColumn('number', 'Average Revenue');
    data.addRows([
      ['2004', 1000, 630],
      ['2005', 1170, 630],
      ['2006', 660, 630],
      ['2007', 1030, 630]
    ]);

    var options = {
      title: 'Revenue by Year',
      seriesType: "bars",
      series: {1: {type: "line"}},  
      vAxis: {title: 'Year',
              titleTextStyle:{color: 'red'}},
        colors:['red','black']
    };

    var chart = new google.visualization.ComboChart(document.getElementById('chart'));
    chart.draw(data, options);
}

google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

Fiddle for the chart: Fiddle

If it could take up a percentage width of a parent it would be great

Advertisement

Answer

The solution was already given online elsewhere.

You need to call your drawChart() function whenever the window is resized to get the desired behaviour. The website flopreynat.com exactly describes this problem and solution (codepen). It describes how this can be done using JQuery:

$(window).resize(function(){
  drawChart();
});

Using just Javascript, this answer on Stack Exchange by Sohnee describes how to trigger functions upon a resize event:

window.onresize = doALoadOfStuff;

function doALoadOfStuff() {
    //do a load of stuff
}

All credit to both authors of the links above.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement