Rishabh Sharma
Rishabh Sharma

Reputation: 33

How to align v axis label w.r.t chart window in google charts?

The y asis labels of my google charts are aligned with respect to the vertical bar while I want them to be aligned with the margin of the chart. I looked everywhere. Can anyone help. The left to right and right to left uses thechart margin as reference not the chart area left margin.

Upvotes: 1

Views: 2000

Answers (2)

Mahesh Panchgade
Mahesh Panchgade

Reputation: 1

Just provide is-stacked as true in option if you want to align Y-axis names with bar

options={ isStacked: true}

Upvotes: 0

WhiteHat
WhiteHat

Reputation: 61232

no options for label alignment...

but you can move them manually when the chart's 'ready' event fires

you can use the following chart method to get the bounds of each label

getChartLayoutInterface().getBoundingBox(id)

then set the labels's x attribute to the same value as the width
if the labels need more room, use option --> chartArea.left

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'x');
  data.addColumn('number', 'y0');
  data.addRows([
     ['Brain Tree', 200],
     ['One Touch', 220],
     ['PayPal Email', 240],
     ['PayPal Here', 260],
     ['PayPal Invoice', 280],
     ['PayPal Mas', 300]
  ]);

  var container = document.getElementById('chart_div');
  var chart = new google.visualization.BarChart(container);

  google.visualization.events.addListener(chart, 'click', function (gglClick) {
    console.log(JSON.stringify(gglClick));
  });

  google.visualization.events.addListener(chart, 'ready', function () {
    var chartLayout = chart.getChartLayoutInterface();
    var labelIndex = -1;
    var labelWidth;

    var axisLabels = container.getElementsByTagName('text');
    Array.prototype.forEach.call(axisLabels, function(label) {
      if (label.getAttribute('text-anchor') === 'end') {
        labelIndex++;
        labelWidth = chartLayout.getBoundingBox('vAxis#0#label#' + labelIndex).width;
        label.setAttribute('x', labelWidth);
      }
    });
  });

  chart.draw(data, {
    chartArea: {
      left: 128
    },
    height: 600
  });
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Upvotes: 1

Related Questions