I'm trying to update my legend in d3.js whenever the data changes. My jsfiddle is supposed to update the legend whenever the key set gets changed. The keyset changes whenever different data is put into the charge using the update date button.
I thought something like this:
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);});
Would update my legend and remove the old labels whenever the key array changes. But it doesn't remove the old label it just adds labels overtop the old one. How can I update my legend to reflect the date?
The problem is that you are creating one g.legend for the legends each time:
var legend = svg.append("g")
.attr("class", "legend")
.attr("height", 100)
.attr("width", 100)
.attr("transform", "translate(-20, 50)");
Instead, you should create it once in initPlot, and then reuse it as var legend = svg.select('g.legend') for the subsequent legend rect and text.
Demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With