google charts move annotation position to center of stacked chart

喜夏-厌秋 提交于 2019-12-02 01:41:16

similar to the other question, just need to a way to find the annotations.
here, we use the text-anchor attribute, assuming it isn't the x-axis label.

then we can use chart method getChartLayoutInterface to calculate the new position.

see following working snippet...

google.charts.load('current', {
  packages:['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Range', 'score range A',{role: 'style'},{ role: 'annotation' }, 'score range B',{role: 'style'},{ role: 'annotation' }, 'score range C', {role: 'style'},{ role: 'annotation' },'score range D', {role: 'style'},{ role: 'annotation' }],
    ['Range', 4,'#D7F0B4','0-4',6,'#00B050','5-10',9,'#92D050','11-19',6, '#AAE182','20-25']
  ]);

  var options = {
    vAxis:{ ticks: [0,4,10,19], viewWindow: { max: 25} },
    isStacked: true,
    title: 'Score',
    legend: {position: 'none'}
  };

  var container = document.getElementById('idealchartA');
  var chart = new google.visualization.ColumnChart(container);

  google.visualization.events.addListener(chart, 'ready', function () {
    var observer = new MutationObserver(moveAnnotations);
    observer.observe(container, {
      childList: true,
      subtree: true
    });
  });

  function moveAnnotations() {
    var chartLayout = chart.getChartLayoutInterface();
    var barBounds;
    var labelBounds;
    var yAdj;

    var labels = container.getElementsByTagName('text');
    var index = 0;
    Array.prototype.forEach.call(labels, function(label) {
      if ((label.getAttribute('text-anchor') === 'middle') && (label.textContent !== data.getValue(0, 0))) {
        barBounds = chartLayout.getBoundingBox('bar#' + index + '#0');
        labelBounds = chartLayout.getBoundingBox('annotationtext#' + index + '#0#0');
        yAdj = (barBounds.height / 2) + (parseFloat(label.getAttribute('font-size')) / 2) - 2;
        label.setAttribute('y', barBounds.top + yAdj);
        index++;
      }
    });
  }

  chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="idealchartA"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!