google charts move annotation position to center of stacked chart

后端 未结 1 365
既然无缘
既然无缘 2021-01-22 04:12

I am using Google Chart\'s column graph chart. The chart is a stacked column chart with annotations for every data point of the stacked column. The annotation are at the top of

相关标签:
1条回答
  • 2021-01-22 04:38

    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>

    0 讨论(0)
提交回复
热议问题