Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 how to update text?

I have created text nodes that has some value. So whenever data updates, only the value should update, the text nodes shouldn't be created again.

systemLevel
.enter()
.append('g')
.classed("system-level", true)
.attr("depth", function(d, i) {
  return i;
})
.each(function(d, i) {
  var columnHeader = graphHeaders.append("g")
                                 .classed("system-column-header", true);
  columnHeader.append('text')
              .attr('font-size', '14')
              .attr('font-weight', 'bold')
              .attr('fill', "red")
              .attr('x', 50 * i)
              .attr('y', 50)
              .text(function() {
                return d.newUser;
              });
  columnHeader.append('text')
              .attr('font-size', '14')
              .attr('font-weight', 'bold')
              .attr('fill', "blue")
              .attr('x', 50* i)
              .attr('y', 70)
              .text(function() {
                return d.value;
              });
});

I have created an example on Js Bin. https://jsbin.com/dixeqe/edit?js,output

I am not sure, how to update just the text value. Any help is appreciated!

like image 495
user2532865 Avatar asked Oct 02 '15 00:10

user2532865


1 Answers

You're not using the usual D3 update pattern, described in many tutorials (e.g. here). You need to restructure the code to use this instead of unconditionally appending new elements:

var columnHeader = graphHeaders.selectAll("g").data(dataset);
columnHeader.enter().append("g").classed("system-column-header", true);
var texts = columnHeader.selectAll("text").data(function(d) { return [d.newUser, d.value]; });
texts.enter().append("text")
  .attr('font-size', '14')
  .attr('font-weight', 'bold')
  .attr('fill', "red")
  .attr('x', function(d, i, j) { return 50 * j; })
  .attr('y', function(d, i) { return 50 + 20 * i; });
texts.text(function(d) { return d; });

Modified jsbin here.

like image 132
Lars Kotthoff Avatar answered Sep 29 '22 11:09

Lars Kotthoff