如何在d3.js中更新我的图例?

时间:2013-11-04 16:20:18

标签: javascript graph d3.js legend

每当数据发生变化时,我都会尝试在d3.js中更新我的图例。每当密钥集发生变化时,我的jsfiddle都应该更新图例。只要使用更新日期按钮将不同的数据输入费用,密钥集就会更改。

我想到这样的事情:

var legendBox = legend.selectAll("rect")
  .data(keys);

legendBox.enter()
  .append("rect");

legendBox.exit()
  .remove();

legendBox.attr("x", width - 150)
  .attr("y", function (d, i) { return i * 20;})
  .attr("width", 10)
  .attr("height", 10)
  .style("fill", function (d, i) { return color(i);});

更新我的图例并在键阵列更改时删除旧标签。但它并没有删除旧标签,它只是添加旧标签。如何更新我的图例以反映日期?

1 个答案:

答案 0 :(得分:3)

问题是你每次为图例创建一个g.legend

var legend = svg.append("g")
    .attr("class", "legend")
    .attr("height", 100)
    .attr("width", 100)
    .attr("transform", "translate(-20, 50)");

相反,您应该在initPlot中创建一次,然后将其重新用作后续图例var legend = svg.select('g.legend')rect的{​​{1}}。

Demo