D3:如何用新数据刷新图表? [英] D3: How to refresh a chart with new data?

查看:34
本文介绍了D3:如何用新数据刷新图表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 d3 圆环图.这是我的代码:

I have created a d3 donut chart. Here is my code:

var width = 480;
var height = 480;
var radius = Math.min(width, height) / 2;
var doughnutWidth = 30;

var color = d3.scale.category10();

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

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

var dataset = settings.dataset;
console.log(dataset);

var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var path = svg.selectAll('path')
.data(pie(dataset))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) { 
  return color(d.data[0]);
})

我的网页上有一个简单的表单,它显示一个带有多个选项的下拉菜单.每次用户更改表单上的值时,都会向我的脚本 (settings.dataset) 发送一个新数据集,并在页面上重新绘制甜甜圈.

I have a simple form on my web page which displays a dropdown menu with several options. Every time a user changes a value on the form a new dataset is sent to my script (settings.dataset) and the donut is redrawn on the page.

问题是,之前数据集中的一些值保留在 DOM 中.在下面的控制台输出中,您可以看到第二个数据集只有两个元素.第三个来自之前的数据集.这弄乱了图表,因为它显示了一个不应该存在的值.

Problem is, some of the values from the previous dataset remain in the DOM. In the console output below, you can see that the second dataset only has two elements. The third one is from the previous dataset. This is messing up the chart, as it is displaying a value that shouldn't be there.

我的问题:如何清除旧值?我已经阅读了 .exit().remove(),但我无法理解这些方法.

My question: how do I clear the old values? I've read up on .exit() and .remove(), but I can't get my head around these methods.

推荐答案

创建一个函数,在创建和更新时(重新)绘制饼图.

Create one function that (re)draws the pie when it's created and when it's updated.

新数据应使用 enter() 添加到饼图,旧数据应使用 exit().remove()

New data should be added to pie using enter() and old data should be removed using exit().remove()

就这么简单:

  path.enter().append("path")
            .attr("fill", function(d, i) { return color(i); })
            .attr("d", arc)
            .each(function(d) {this._current = d;} );

  path.transition()
            .attrTween("d", arcTween);

  path.exit().remove()

完整的工作代码 -> JSFIDDLE

Full working code -> JSFIDDLE

这篇关于D3:如何用新数据刷新图表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆