【问题标题】:Use pies as points in a line chart and change the radius of the pie将饼图用作折线图中的点并更改饼图的半径
【发布时间】:2016-06-24 04:11:09
【问题描述】:

我有一个折线图(或者,更准确地说是一个连接的散点图),我在这些点周围绘制馅饼/甜甜圈。因此,有一个数据集指定绘制点的日期和心情以及其他两个参数 pos 和 neg,提供进入饼图的值。描述点的整体数据称为 plotPoints。

这一切都很好,但我仍然想做的是将饼图的半径设置为 pos + neg 之和的函数。

当我绘制出点时,我可以使用函数 (d) 访问所有数据。然而,在每个饼图中,function(d) 一次返回一个关于切片的数据。 d 包含当前切片的数据,而不是整体数据。对于每个饼图,第一次调用弧时它具有第一个饼图切片的频率,第二次调用它具有第二个饼图切片的频率。

如何在绘制圆弧时参考当前的 plotPoints 属性,以便我可以更改饼图/甜甜圈的半径来表示 plotPoints[i].pos + plotPoints[i].neg 的总和?

相关代码如下:

  var arc = d3.svg.arc()
    .outerRadius(radius - 10)
    .innerRadius(8);

  var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) { return d; });


  var p = moodChart.selectAll(".pieContainer")
    .data(plotPoints).enter()
    .append("g")
    .attr("class","pieContainer")
    .attr("transform", function(d,i) {return "translate(" + (x(d.date)) + "," + (y(d.mood)) + ")"});
    p.append("title")
        .text(function(d) { return shortDateFormat(d.date) +", " + d.mood.toFixed(2) });


 var g = p.selectAll(".arc")
  .data(function (d) {return pie([d.neg, d.pos])})
.enter().append("g")
  .attr("class", "arc");




  g.append("path")
    .attr("d", arc)
    .style("fill", function(d,i) { return i==0 ? "brown" : "green"; });

【问题讨论】:

    标签: d3.js pie-chart linechart


    【解决方案1】:

    如果没有更多代码/数据来查看,很难权威地回答这个问题但是在这种情况下,我通常 stash 在我的数据绑定中需要的变量,以便它们稍后可用:

    var g = p.selectAll(".arc")
      .data(function (d) {
        var total = d.neg + d.pos,
          pie_data = pie([d.neg, d.pos]),
          point_arc = d3.svg.arc()
            .outerRadius((total * radius) - 10) //<-- set radius based on total
            .innerRadius((total * radius) - 8);
    
        pie_data.forEach(function(d1){
          d1.data.arc = point_arc; //<-- stash the arc for this point in our data bindings
        });
    
        return pie_data;
      });
      .enter().append("g")
      .attr("class", "arc");
    
      g.append("path")
        .attr("d", function(d){
          return d.data.arc
        })
        .style("fill", function(d,i) { return i==0 ? "brown" : "green"; });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多