【问题标题】:How to obtain percentage in tooltips of an nvd3 pie chart?如何在 nvd3 饼图的工具提示中获取百分比?
【发布时间】:2014-08-28 17:12:36
【问题描述】:

我有一个 nvd3 饼图。我正在获取百分比值作为标签,但我希望它在工具提示中。这是 HTML:

<nvd3-pie-chart data="Data1"id="labelTypePercentExample"
      width="550"
      height="350"
      x="xFunction()"
      y="yFunction()"
      showLabels="true"
      pieLabelsOutside="false"
      tooltips="true"
      tooltipcontent="toolTipContentFunction()"
      labelType="percent"
      showLegend="true">
  </nvd3-pie-chart>

数据

Data1=[{ key: "Ongoing", y: 20 },
       { key: "completed", y: 0 }];

这里是用于将键显示为工具提示数据的工具提示功能。

$scope.toolTipContentFunction = function(){
    return function(key, x, y, e, graph) {
       return '<h1>' + key + '</h1>'
    }
}

【问题讨论】:

    标签: javascript svg d3.js pie-chart nvd3.js


    【解决方案1】:

    这是一个jsfiddle,它在工具提示中显示百分比。

    关键代码是这样的:(您必须计算构成饼图的所有值的总和)

    var data = [
        {"label": "Water",        "value": 63}, 
        {"label": "Milk",         "value": 17}, 
        {"label": "Lemonade",     "value": 27},
        {"label": "Orange Juice", "value": 32}
    ];
    
    var total = 0;
    data.forEach(function (d) {
        total = total + d.value;
    });
    var tp = function(key, y, e, graph) {
        return '<p>' +  (y * 100/total).toFixed(3) + '%</p>';
    };
    

    此外,您在创建 NVD3 图表时添加此行,您已经知道:

    .tooltipContent(tp);
    

    最终结果:

    【讨论】:

      【解决方案2】:

      稍微修改了@VividD 的答案。

      可以(nvd3 v 1.8.1)只修改工具提示中的值(不是所有文本):

      var total = 0;
      data.forEach(function (d) {
          total = total + d.value;
      });
      
      chart.tooltip.valueFormatter(function(d){
          return (d * 100/total).toFixed() + ' %';
      });
      

      示例:http://jsfiddle.net/mq56p4zk/4/

      【讨论】:

      • 能否请您详细说明您的答案,添加更多关于您提供的解决方案的描述?
      【解决方案3】:

      类似于 workgena,这是为我做的。

      chart.tooltip.valueFormatter(function(d){
          return (d +' %');
      });
      

      【讨论】:

      • 这只会在值后面添加一个百分号,看起来不像是 OP 想要的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 2015-02-17
      • 2021-12-10
      相关资源
      最近更新 更多