开发者

Text not updating dynamically with d3 after using d3.exit().remove()

开发者 https://www.devze.com 2022-12-07 21:35 出处:网络
So I am building an interactive dashboard, in that whenever you click on a button the bar graph changes something like this (https://d3-graph-gallery.com/graph/barplot_button_data_hard.html)

So I am building an interactive dashboard, in that whenever you click on a button the bar graph changes something like this (https://d3-graph-gallery.com/graph/barplot_button_data_hard.html)

In my code, I am trying to update the title of the bar graph as well by doing this

var t = svg_bar_graph_time_date.selectAll("label").data(data_bar_graph_time_date)

                t.enter()
                .append("text")
                .attr("x", width_time_date/2)
                .attr("y", 20)
                .attr("text-anchor", "middle")
                .style("font-size", "16px")
                .text(date);
            开发者_高级运维    
                t.exit().remove()

But instead of changing the title of the bar graph, the new title is overlapping over the previous one. How can I remove the previous title and change it new one?


Since you're biding the data to elements that have the label class (unless you're selecting a <label> element, which doesn't seem to be the case)...

var t = svg_bar_graph_time_date.selectAll(".label")
    .data(data_bar_graph_time_date);

... you need to apply that class to the enter selection, and merge it with the update selection:

t = t.enter()
    .append("text")
    .attr("class", "label")
    .attr("x", width_time_date/2)
    .attr("y", 20)
    .attr("text-anchor", "middle")
    .style("font-size", "16px")
    .merge(t)
    .text(date);

If you're using a D3 version without merge, change the update selection:

t.text(date);

Also, it's strange that you're binding data but never use it (you're using date, but isn't clear where that is coming from). If that's intended, drop the exit selection and just do data([true]) or any other non-empty one-element array.

0

精彩评论

暂无评论...
验证码 换一张
取 消