【问题标题】:show percentage in d3 pie chart在 d3 饼图中显示百分比
【发布时间】:2016-07-24 08:42:47
【问题描述】:

目前我在 d3 中的饼图显示数字的总和,我想要百分比。

例如:目前我有一个饼图,显示有多少人提交了访问我们网站的申请。我们当前的饼图显示如下:人们提交了 17,000,人们没有提交 - 10,000 但我也需要这个百分比。我怎么能得到那个。 请在下面找到饼图代码,让我知道我需要进行哪些更改才能使其正常工作。我是 JavaScript 和 D3 的新手。

ko.bindingHandlers.pieChart = {
    init: function (element, valueAccessor) {
      var _options = valueAccessor();
      var _data = _options.transformer(_options.data);
      $(element).css("marginLeft", "auto");
      $(element).css("marginRight", "auto");
      if (typeof _options.maxWidth != "undefined") {
        var _max = _options.maxWidth * 1;
        $(element).width(Math.min($(element).parent().width(), _max));
      }

      if ($(element).find("svg").length > 0 && _data.length == 0) {
        $(element).find("svg").empty();
      }

      if (_data.length > 0 && isNaN(_data[0].value)) {
        _data = [];
        $(element).find("svg").empty();
      }

      if ($(element).is(":visible")) {
        nv.addGraph(function () {
          var _chart = nv.models.growingPieChart()
              .x(function (d) {
                return d.label
              })
              .y(function (d) {
                return d.value
              })
              .height($(element).width())
              .showLabels(true).showLegend(false)
              .tooltipContent(function (key, y, e, graph) {
                return '<h3>' + hueUtils.htmlEncode(key) + '</h3><p>' + y + '</p>'
              });

          var _d3 = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");

          _d3.datum(_data)
              .transition().duration(150)
              .each("end", _options.onComplete != null ? _options.onComplete : void(0))
              .call(_chart);

          if (_options.fqs) {
            $.each(_options.fqs(), function (cnt, item) {
              if (item.id() == _options.data.widget_id && item.field() == _options.field()) {
                _chart.selectSlices($.map(item.filter(), function (it) {
                  return it.value();
                }));
              }
            });
          }

          $(element).data("chart", _chart);

          var _resizeTimeout = -1;
          nv.utils.windowResize(function () {
            window.clearTimeout(_resizeTimeout);
            _resizeTimeout = window.setTimeout(function () {
              _chart.update();
            }, 200);
          });

          $(element).on("forceUpdate", function () {
            _chart.update();
          });

          $(element).height($(element).width());
          var _parentSelector = typeof _options.parentSelector != "undefined" ? _options.parentSelector : ".card-widget";
          $(element).parents(_parentSelector).on("resize", function () {
            if (typeof _options.maxWidth != "undefined") {
              var _max = _options.maxWidth * 1;
              $(element).width(Math.min($(element).parent().width(), _max));
            }
            $(element).height($(element).width());
            _chart.update();
          });

          return _chart;
        }, function () {
          var _d3 = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");
          _d3.selectAll(".nv-slice").on("click",
              function (d, i) {
                if (typeof _options.onClick != "undefined") {
                  chartsUpdatingState();
                  _options.onClick(d);
                }
              });
        });
      }
    },
    update: function (element, valueAccessor) {
      var _options = valueAccessor();
      var _data = _options.transformer(_options.data);
      var _chart = $(element).data("chart");
      if (_chart) {
        var _d3 = d3.select($(element).find("svg")[0]);
        _d3.datum(_data)
              .transition().duration(150)
              .each("end", _options.onComplete != null ? _options.onComplete : void(0))
              .call(_chart);

        if (_options.fqs) {
            $.each(_options.fqs(), function (cnt, item) {
              if (item.id() == _options.data.widget_id && item.field() == _options.field()) {
                _chart.selectSlices($.map(item.filter(), function (it) {
                  return it.value();
                }));
              }
            });
          }
        chartsNormalState();
      }
      else if (_data.length > 0) {
        ko.bindingHandlers.pieChart.init(element, valueAccessor);
      }
    }
  };

【问题讨论】:

    标签: d3.js pie-chart percentage


    【解决方案1】:

    一个小提琴对于测试这个(提示提示)很有用,但我很确定你想改变这一行:

    .y(function (d) {
      return d.value
    })
    

    到这里

    .y(function (d) {
      return d.value/total
    })
    

    您可能必须定义总计。就像我说的那样,如果没有 jsfiddle 或者至少没有一些数据格式的指示,就很难确定这是否真的是问题所在或如何修复它。

    注意:相对百分比的饼图看起来与原始数字的饼图完全相同。您也许可以更改标签并且只更改标签,如下所示:

    return '<h3>' + hueUtils.htmlEncode(key) + '</h3><p>' + y + '</p>'
    

    到这里

    return '<h3>' + hueUtils.htmlEncode(key) + '</h3><p>' + (y/total) + '</p>'
    

    希望这两个都可以。如果尚未在其他地方定义,您将必须定义总计。如果没有:

    var total = 0;
    _data.forEach(function(d){total += d.value});
    

    祝你好运!

    【讨论】:

    • 感谢 Vyross 的回复。我是 Js 新手,请确认以下更改是否符合您的意思;
    • if ($(element).is(":visible")) { nv.addGraph(function () { var _chart = nv.models.growthPieChart() .x(function (d) { return d.label }) .y(function (d) { var total=0; _data.forEach(function(d){total +=d.value}) return d.value/total }) .height($(element ).width()) .showLabels(true).showLegend(false) .tooltipContent(function (key, y, e, graph) { return '

      ' + hueUtils.htmlEncode(key) + '

      ' + (y/total) + ''
    • 您只想定义一次总和,再往上 - 我会在定义 var _data 后立即执行。
    • 甚至 _data.forEach(function(d){total +=d.value}) 需要定义得更远
    【解决方案2】:

    包含您正在使用的库之类的信息以及使用 gist、codepen、jsfiddle 等完全可重现的示例会更有帮助。我猜您正在使用hue,更具体地说是growingPieChart。如果我的猜测是正确的,那么您可以修改您的tooltipContent 函数,类似于我输入此内容时发布的@Vyross 答案。

    .tooltipContent(function (key, y, e, graph) {
      return '<h3>' + hueUtils.htmlEncode(key) + '</h3><p>' +
        (+y) / d3.sum(
          d3.select(graph.container).select('g').datum(),
          function(d){return d.value}
        ) +
        '</p>'
    });
    

    【讨论】:

    • 是的,我们正在使用 Hue,我不知道这个饼图是基于哪个库构建的。但我认为他们可能从 gitbash 复制了源代码。
    • 我们尝试了此工具提示更改,但现在我们看到的是 NaN 而不是百分位数。
    • y 可能是一个字符串,所以尝试使用+(y)。我改变了答案。
    • 如果不行,可以尝试将d.value改成合适的字段。
    猜你喜欢
    • 2015-03-02
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多