【问题标题】:Show only percentage in Google Visualization Chart API在 Google Visualization Chart API 中仅显示百分比
【发布时间】:2018-07-15 17:39:03
【问题描述】:

是否可以在 Google Visualization Chart API 中只显示百分比?

我在docs 中找不到任何相关信息

我有pieSliceText: 'percentage',但我也想在鼠标悬停时只显示 %。

【问题讨论】:

    标签: charts google-visualization


    【解决方案1】:

    您可以提供自己的自定义工具提示

    这里,group 方法用于求所有行的总和...

      var total = google.visualization.data.group(
        data,
        [{column: 0, modifier: function () {return 'total'}, type:'string'}],
        [{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
      );
    

    然后使用数据视图添加工具提示列,其中计算百分比...

      var view = new google.visualization.DataView(data);
      view.setColumns([0, 1, {
        type: 'string',
        role: 'tooltip',
        calc: function (dt, row) {
          var percent = (dt.getValue(row, 1) / total.getValue(0, 1)) * 100;
          return '<div class="tooltip">' + dt.getValue(row, 0) + ':&nbsp;<span>' + percent.toFixed(1) + '%</span>';
        },
        p: {html: true}
      }]);
    

    请参阅以下工作 sn-p...

    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    
    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['Task', 'Hours per Day'],
        ['Work',     11],
        ['Eat',      2],
        ['Commute',  2],
        ['Watch TV', 2],
        ['Sleep',    7]
      ]);
    
      var options = {
        title: 'My Daily Activities',
        pieSliceText: 'percentage',
        tooltip: {
          isHtml: true
        }
      };
    
      var total = google.visualization.data.group(
        data,
        [{column: 0, modifier: function () {return 'total'}, type:'string'}],
        [{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
      );
    
      var view = new google.visualization.DataView(data);
      view.setColumns([0, 1, {
        type: 'string',
        role: 'tooltip',
        calc: function (dt, row) {
          var percent = (dt.getValue(row, 1) / total.getValue(0, 1)) * 100;
          return '<div class="tooltip">' + dt.getValue(row, 0) + ':&nbsp;<span>' + percent.toFixed(1) + '%</span>';
        },
        p: {html: true}
      }]);
    
      var chart = new google.visualization.PieChart(document.getElementById('piechart'));
      chart.draw(view.toDataTable(), options);
    }
    .tooltip {
      font-size: 12pt;
      padding: 6px;
    }
    
    .tooltip span {
      font-weight: bold;
    }
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="piechart"></div>

    【讨论】:

      猜你喜欢
      • 2011-09-22
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多