wtreston
wtreston

Reputation: 1061

Align Google Visualization Pie Chart so Chart is in centre of page

This is what the pie charts currently look like

Currently the charts look like this

This is the code I am use:

<div id="{{ question.0.name }}" style="width: 100%; height: 400px;"></div>

<script type="text/javascript">
    google.charts.load('current', { 'packages': ['corechart'] });
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {

        var data = google.visualization.arrayToDataTable([
            ['Score', 'Amount'],
            ['1', {{ question.1.0}}],
            ['2', {{ question.1.1}}],
            ['3', {{ question.1.2}}],
            ['4', {{ question.1.3}}],
            ['5', {{ question.1.4}}]
        ]);

        var chart = new google.visualization.PieChart(document.getElementById('{{ question.0.name }}'));

        chart.draw(data);
    }
</script>

I'm using Jinja2 Variables to populate the fields but they seem to be working. I want to align the Pie Chart so that it sits in the middle of the page. Any Idea how I can do that?

Upvotes: 0

Views: 3198

Answers (1)

WhiteHat
WhiteHat

Reputation: 61275

PieChart is probably the most difficult when it comes to sizing and placement

to get the pie in the center of the container,
the easiest change would be to place the legend on top or bottom.

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Label', 'Value'],
    ['3', 33.3],
    ['5', 66.7]
  ]);

  var options = {
    height: 400,
    legend: {
      alignment: 'center',
      position: 'top'
    }
  };

  var container = document.getElementById('chart_div');
  var chart = new google.visualization.PieChart(container);
  chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

otherwise, you can try adjusting chartArea.width...

var options = {
  chartArea: {
    width: '40%',
  },

Upvotes: 1

Related Questions