Search code examples
jqueryhtmlcsschartsgoogle-visualization

Sizing Google charts to fill div width and height


Just getting started in Google charts and I'm trying to create a line graph that fills the available space. Seems like the charts are locked in a certain aspect ratio though as no matter what I change the height and width properties to for the chart and chart div element, the result doesn't match my dimensions.

Are Google charts fixed that way or is there an override or aspect ratio option that I am missing?

You can find an example here:

http://www.walkingcarpet.net/graphs/unemployment-rate/

Thanks!


Solution

  • in addition to setting the width option,

    set chartArea.width to ensure the chart utilizes the available space

    also, when the window is resized, the chart needs to be redrawn

    see following working snippet...

    google.charts.load('current', {
      callback: function () {
        drawChart();
        $(window).resize(drawChart);
      },
      packages:['corechart']
    });
    
    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['x', 'y'],
        [0, 0],
        [1, 1],
        [2, 3],
        [3, 7],
        [4, 15],
        [5, 31]
      ]);
    
      var options = {
        chartArea: {
          // leave room for y-axis labels
          width: '94%'
        },
        legend: {
          position: 'top'
        },
        width: '100%'
      };
    
      var container = document.getElementById('chart_div');
      var chart = new google.visualization.LineChart(container);
      chart.draw(data, options);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="chart_div"></div>


    EDIT

    among others, chartArea also has a property for left

    instead of using chartArea.width: '94%'

    try setting an absolute left

    see following working snippet...

    google.charts.load('current', {
      callback: function () {
        drawChart();
        $(window).resize(drawChart);
      },
      packages:['corechart']
    });
    
    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['x', 'y'],
        [0, 0],
        [1, 1],
        [2, 3],
        [3, 7],
        [4, 15],
        [5, 31]
      ]);
    
      var options = {
        chartArea: {
          left: 40,
          width: '100%'
        },
        legend: {
          position: 'top'
        },
        width: '100%'
      };
    
      var container = document.getElementById('chart_div');
      var chart = new google.visualization.LineChart(container);
      chart.draw(data, options);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="chart_div"></div>