Javascript 如何在d3.js中更新图形图例?

Javascript 如何在d3.js中更新图形图例?,javascript,graph,d3.js,legend,Javascript,Graph,D3.js,Legend,每当数据发生变化时,我都会尝试更新d3.js中的图例。My应该在密钥集更改时更新图例。每当使用“更新日期”按钮将不同的数据输入电荷时,钥匙集就会发生变化 我是这样想的: var legendBox = legend.selectAll("rect") .data(keys); legendBox.enter() .append("rect"); legendBox.exit() .remove(); legendBox.attr("x", width - 150) .att

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

我是这样想的:

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);});

将在密钥数组更改时更新我的图例并删除旧标签。但它不会删除旧标签,只是在旧标签的上方添加标签。如何更新图例以反映日期?

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

var legend=svg.append(“g”)
.attr(“类”、“图例”)
.attr(“高度”,100)
.attr(“宽度”,100)
.attr(“转换”、“翻译(-20,50)”);
相反,您应该在
initPlot
中创建一次,然后将其作为
var legend=svg重新使用。对于后续的图例
rect
text
,请选择('g.legend')