首页 > 解决方案 > 更新d3中的值时如何在饼图中进行平滑过渡?

问题描述

我正在使用 j3.ds 在饼图上部署一些数据。它似乎工作正常,当我引入新数据时它会正确更新。问题是,我想在顺利更新时进行过渡,如下所示:

https://www.d3-graph-gallery.com/graph/pie_changeData.html

由于某种原因,当我引入合并和转换时它不起作用,有人可以帮助完成任务吗?提前致谢

update();

function update() {

  var data = d3.selectAll('.values').nodes();
  

  var pie = d3.pie()   //we create this variable, for the values to be readeable in the console
    .value(function(d) {return d.innerHTML; })(data);
  console.log("pie = ",pie) 


  var u = svg.selectAll("path")
    .data(pie)
  
  console.log("u = ",u)
   
 // Build the pie chart: Basically, each part of the pie is a path that we build using the arc function

u
    .enter()
    .append('path')
    .merge(u)
    .transition()
    .duration(2000)

    .attr('d', d3.arc()
      .innerRadius(0)        
      .outerRadius(radius)
    )
    
    .attr('fill', function(d,i){ return color[i] })
    .attr("stroke", "black")
    .style("stroke-width", "2px")
    .style("opacity", 1)

}

在此处输入图像描述

标签: javascriptd3.jsdata-visualization

解决方案


合并将一个选择与另一个组合如下:

 selectionCombined = selection1.merge(selection2);

你没有提供第二个选择,所以你没有合并任何东西。您正在调用.merge()的选择是输入选择,由返回.enter()- 除非您向饼图添加新切片,否则在第一次更新后每次更新都将为空。由于您没有将任何内容与输入选择合并,因此合并后选择仍然为空。

输入选择用于创建元素,以便对于数据数组中的每一项在 DOM 中都有一个对应的元素 - 因为您已经有了切片,所以只有更新选择不为空。

更新选择是由 返回的.data(),它包含与数据数组中的项目相对应的现有元素。您想将此选择与返回的选择合并.enter()

var update =  svg.selectAll("path")
    .data(pie)

var enter = update.enter()
    .append('path')

var merged = update.merge(enter)

但是,转换需要一个开始值和一个结束值。在您的情况下,您正在转换d路径的属性。更新时,起始值是路径的当前d值,结束值是d表示切片的新值的 a。在初始进入时,转换应该从什么值开始?仅在更新时转换可能更合适:

var arc = d3.arc().innerRadius(0).outerRadius(radius);

var update =  svg.selectAll("path")
    .data(pie)

var enter = update.enter()
    .append('path')
    // Set initial value:
    .attr('d', arc)
    // If these values don't change, set only on enter: 
    .attr('fill', function(d,i){ return color[i] })
    .attr("stroke", "black")
    .style("stroke-width", "2px")

update.transition()
   // transition existing slices to reflect new data.
   .attr('d',arc)

注意:过渡路径可能很困难 - 您会在示例中注意到过渡中的饼图变形。这是因为d属性字符串的插值方式。如果要保留半径,则需要在应用过渡时采用不同的方法。


推荐阅读