如何在Google Pie Chart中添加图例和标签?

时间:2013-12-11 17:58:15

标签: javascript charts google-visualization

如何设置Google饼图的图例和标签?

弃用的方法具有此功能:https://developers.google.com/chart/image/docs/gallery/pie_charts

另外,我怎样才能让所选切片在馅饼上点亮一点?

这是我到目前为止所拥有的:

  <div id="pie_chart_div" style="width: 940px; height: 500px;"></div>

  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <script type="text/javascript">
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(render_applicant_sources);

    function render_applicant_sources() {
      var data = new google.visualization.arrayToDataTable([["Source","Number of Applicants"],["Hospitality Online",222],["Indeed",22]]);

      data.addColumn('string', 'Geocoder');
      data.addColumn('number', 'Geocodes');

      var chart = new google.visualization.PieChart(document.getElementById('pie_chart_div'));

      var options = {
          title: 'Scottsdale Resort & Conference Center from December  1, 2012 to December  1, 2013',
          is3D: true,
          colors: [ '#2483b3', '#AAC789', '#1E4147', '#437356', '#F34A53', '#FAE3B4' ],
          titleTextStyle: { bold: false },
          legend: { position: 'labeled' }
      };

      chart.draw(data, options);

      google.visualization.events.addListener(chart, 'click', function(e){
        var data = chart.getSelection();
        if(data.length > 0) {
            chart.setSelection([]);
        }
      });
    }
  </script>

http://jsfiddle.net/xHwZW/

1 个答案:

答案 0 :(得分:4)

您需要使用“select”事件处理程序,并设置图表的slices.<slice index>.offset选项:

google.visualization.events.addListener(chart, 'select', function() {
    var selection = chart.getSelection();
    if (selection.length > 0) {
        if (!options.slices || !options.slices[selection[0].row]) {
            // if this is the first time the user clicked on the pie,
            // or if the user clicks on an unexploded slice,
            // unexplode all slices and explode the selected slice
            options.slices = [];
            options.slices[selection[0].row] = {
                offset: 0.4
            };
        }
        else {
            // otherwise the user clicked on an exploded slice, so unexplode all slices
            options.slices = [];
        }
        chart.draw(data, options);
    }
    else {
        options.slices = [];
        chart.draw(data, options);
    }
});

参见工作示例:http://jsfiddle.net/asgallant/R8yAK/