Google图表栏水平移动注解位置到堆叠图表的中心

问题描述 投票:2回答:1

我正在使用Google Chart的柱形图。该图表是一个堆积的柱形图,其中包含对于堆积的列的每个数据点的注释。注释位于栏内部的右侧,但我希望它们位于栏内部的中心。

我正在寻找一个开始解决方案的页面。This page带有功能“ moveAnnotations()”,但是我无法获取水平条形图的代码。

感谢您的帮助,我迷路了。 :(

 
/** Valeurs pour le graph bar 1 */
var data_graph_bar_1 = [
    ['Years', 'Beer & other', 'Water', 'CSD', 'Sensitive'],
    ['2014', 71, 56, 79, 59],
    ['2019', 70, 74, 75, 65]
];
 
        // Load the Visualization API and the corechart package.
        google.charts.load('current', {'packages':['corechart']});

        // Set a callback to run when the Google Visualization API is loaded.
        google.charts.setOnLoadCallback(function(){drawChart(data_graph_bar_1)});

        // Callback that creates and populates a data table,
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart(datas) {

            var data = google.visualization.arrayToDataTable(datas);
            var view = new google.visualization.DataView(data);

            view.setColumns([0,
                1, {
                calc: function (dt, row) {
                    return dt.getValue(row, 1);
                },
                type: "number",
                role: "annotation"
                },
                2, {
                calc: function (dt, row) {
                    return dt.getValue(row, 2);
                },
                type: "number",
                role: "annotation"
                },
                3, {
                calc: function (dt, row) {
                    return dt.getValue(row, 3);
                },
                type: "number",
                role: "annotation"
                },
                4, {
                calc: function (dt, row) {
                    return dt.getValue(row, 4);
                },
                type: "number",
                role: "annotation"
                },
                {
                calc: function (dt, row) {
                    return 0;
                },
                label: "Total",
                type: "number",
                },
                {
                calc: function (dt, row) {
                    return dt.getValue(row, 1) + dt.getValue(row, 2)+ dt.getValue(row, 3)+ dt.getValue(row, 4);
                },
                type: "number",
                role: "annotation"
                }
            ]);
            var options = {
                height: 130,
                colors: ['#B4CC00', '#3399FF', '#E64B00','#FF8B00'],
                legend: 'none',
                bar: { groupWidth: '75%' },
                isStacked: true,
                displayAnnotations: true,
                annotations: {
                    textStyle: {
                    // The color of the text.
                        color: '#000000',
                        fontSize: 15
                    },
                },
                hAxis: {
                    gridlines: {
                        count: 0
                    },
                    textPosition: 'none',
                    textStyle : {
                        fontSize: 15
                    }
                },
                vAxis: {
                    textStyle: {
                        bold: true,
                        fontSize: '20',
                    }
                },
                chartArea:{
                    left:50,
                },
            };
            
            // Instantiate and draw our chart, passing in some options.
            var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
            chart.draw(view, options);
        }
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
charts annotations google-visualization stacked-chart react-google-charts
1个回答
0
投票

而不是调整标签的'y'属性,我们只需要调整'x'属性...

首先,我们需要找到注释标签。在这里,我们循环所有行和列,然后使用该值查找标签。

我们排除黑色标签,因为这些标签显示在工具提示中,我们不想移动那些。

  for (var r = 0; r < data.getNumberOfRows(); r++) {
    for (var c = 1; c < data.getNumberOfColumns(); c++) {
      var labels = chart.getContainer().getElementsByTagName('text');
      Array.prototype.forEach.call(labels, function(label, index) {
        if ((label.textContent === data.getValue(r, c).toFixed(0)) &&
            (label.getAttribute('fill') !== '#000000')) {
          barBounds = chartLayout.getBoundingBox('bar#' + (c - 1) + '#' + r);
          xAdj = (barBounds.width / 2);
          label.setAttribute('x', barBounds.left + xAdj);
          label.setAttribute('text-anchor', 'middle');
        }
      });
    }
  }

请参阅以下工作片段...

var data_graph_bar_1 = [
    ['Years', 'Beer & other', 'Water', 'CSD', 'Sensitive'],
    ['2014', 71, 56, 79, 59],
    ['2019', 70, 74, 75, 65]
];

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(function(){drawChart(data_graph_bar_1)});

function drawChart(datas) {

    var data = google.visualization.arrayToDataTable(datas);
    var view = new google.visualization.DataView(data);

    view.setColumns([0,
        1, {
        calc: function (dt, row) {
            return dt.getValue(row, 1);
        },
        type: "number",
        role: "annotation"
        },
        2, {
        calc: function (dt, row) {
            return dt.getValue(row, 2);
        },
        type: "number",
        role: "annotation"
        },
        3, {
        calc: function (dt, row) {
            return dt.getValue(row, 3);
        },
        type: "number",
        role: "annotation"
        },
        4, {
        calc: function (dt, row) {
            return dt.getValue(row, 4);
        },
        type: "number",
        role: "annotation"
        },
        {
        calc: function (dt, row) {
            return 0;
        },
        label: "Total",
        type: "number",
        },
        {
        calc: function (dt, row) {
            return dt.getValue(row, 1) + dt.getValue(row, 2)+ dt.getValue(row, 3)+ dt.getValue(row, 4);
        },
        type: "number",
        role: "annotation"
        }
    ]);
    var options = {
        height: 130,
        colors: ['#B4CC00', '#3399FF', '#E64B00','#FF8B00'],
        legend: 'none',
        bar: { groupWidth: '75%' },
        isStacked: true,
        displayAnnotations: true,
        annotations: {
            textStyle: {
            // The color of the text.
                color: '#000000',
                fontSize: 15
            },
        },
        hAxis: {
            gridlines: {
                count: 0
            },
            textPosition: 'none',
            textStyle : {
                fontSize: 15
            }
        },
        vAxis: {
            textStyle: {
                bold: true,
                fontSize: '20',
            }
        },
        chartArea:{
            left:50,
        },
    };

    // Instantiate and draw our chart, passing in some options.
    var chart = new google.visualization.BarChart(document.getElementById('chart_div'));

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

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

      for (var r = 0; r < data.getNumberOfRows(); r++) {
        for (var c = 1; c < data.getNumberOfColumns(); c++) {
          var labels = chart.getContainer().getElementsByTagName('text');
          Array.prototype.forEach.call(labels, function(label, index) {
            if ((label.textContent === data.getValue(r, c).toFixed(0)) && (label.getAttribute('fill') !== '#000000')) {
              barBounds = chartLayout.getBoundingBox('bar#' + (c - 1) + '#' + r);
              xAdj = (barBounds.width / 2);
              label.setAttribute('x', barBounds.left + xAdj);
              label.setAttribute('text-anchor', 'middle');
            }
          });
        }
      }
    }

    chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
© www.soinside.com 2019 - 2024. All rights reserved.