每当数据发生变化时,我都会尝试在 d3.js 中更新我的图例。我的jsfiddle应该在键集更改时更新图例。每当使用更新日期按钮将不同的数据放入收费中时, key 集就会发生变化。
我是这样想的:
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);});
只要键数组发生变化,就会更新我的图例并删除旧标签。但它不会删除旧标签,它只是在旧标签上添加标签。如何更新图例以反射(reflect)日期?
最佳答案
问题是您每次都为图例创建一个 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
和 text
。
Demo .
关于javascript - 如何在 d3.js 中更新图表图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19772124/