How can I position a Google chart in a webpage?

13,600

Solution 1

For example to position the chart at (0,0) within the DIV, add to the chart options :

var options = {
          ...,
          chartArea:{left:0,top:0,width:"50%",height:"50%"}
}

and adjust the width and height as you want; the full options are here.

Solution 2

OK, you need to add some extra HTML:

<body>
    <div style="position:relative;width:100%">
        <div id="chart_div" style="position:absolute;right:0px;top:0px;width: 400px; height: 300px;"></div>
    </div>
</body>

The height of the chart can be controlled by the width and height of the div. The placement can be controlled by changing, right, top, of changing to left/bottom, etc.

You may want to float the chart_div, or use any other method of positioning.

Depending on your requirements, this may be enough: If not, let me know.

Share:
13,600
AturSams
Author by

AturSams

Indie Dev

Updated on June 17, 2022

Comments

  • AturSams
    AturSams almost 2 years

    I am using Google chart. The positioning eludes me. I haven't located that part in the documentation. I simply want to create a Google chart inside a div with the top left corner positioned in (x, y) in the div. Extra points for help with controlling the dimensions.

    <html>
      <head>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
          google.load("visualization", "1", {packages:["corechart"]});
          google.setOnLoadCallback(drawChart);
          function drawChart() {
            var data = google.visualization.arrayToDataTable([
              ['Year', 'Sales', 'Expenses'],
              ['2004',  1000,      400],
              ['2005',  1170,      460],
              ['2006',  660,       1120],
              ['2007',  1030,      540]
            ]);
    
            var options = {
              title: 'Company Performance',
              hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
            };
    
            var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
            chart.draw(data, options);
          }
        </script>
      </head>
      <body>
        <div id="chart_div" style="width: 900px; height: 500px;"></div>
      </body>
    </html>
    

    If I look in the html in 'runtime' using a tool like firebug I see:

    rect x="161" y="96" width="579" height="309"
    

    But I did not pick any of those values.

    • AturSams
      AturSams over 11 years
      Ok, I went ahead and added some :)