jasondavies / d3-cloud

Create word clouds in JavaScript.
https://www.jasondavies.com/wordcloud/
Other
3.85k stars 1.07k forks source link

Update an existing graph could be a nice addition to examples #160

Open naholyr opened 5 years ago

naholyr commented 5 years ago

Having no experience in D3, it took me a while to figure out why a graph would only be partially updated… Your samples include the .enter() case, so new words can be added. But existing words do not get their size updated, nor the removed words can actually be removed, unless you specifically add this to your draw function…

For any other newbie fighting to update their graph, here is how I did it:

    const n = this._vis.selectAll('text')
      .data(words, d => d.text); // second parameter = unique key (don't set and adding words will miserably fail)

    // Updated words
    n
      .style('font-weight', d => d.weight)
      .style('fill', t => this._color ? this._color(t.text) : '')
      .transition().duration(transition)
        .attr('transform', t => 'translate(' + [t.x, t.y] + ')rotate(' + t.rotate + ')') // animate new position
        .style('font-size', d => d.size + fontSizeUnit); // animate new size

    // Append new words
    n.enter().append('text')
      .style('font-family', d => d.font)
      .style('font-style', d => d.style)
      .style('font-weight', d => d.weight)
      .attr('text-anchor', 'middle')
      .attr('transform', t => 'translate(' + [t.x, t.y] + ')rotate(' + t.rotate + ')') // animates position
      .text(d => d.text)
      .style('font-size', '1px').transition().duration(transition).style('font-size', d => d.size + fontSizeUnit); // animates word's size

    // Remove deleted words
    n.exit()
      .transition().duration(transition)
        .style('font-size', '0px')
        .style('opacity', 0)
      .remove();

Is it the right way? Shouldn't be it included in provided examples?