Search code examples
javascriptd3.jsupdatestag-cloudword-cloud

Update words(size change or remove words) in D3 word cloud without changing their position?


I am using the word cloud library in D3 by Jason Davies. This is the normal code which I am using and works fine for creating the word clouds.

    d3.layout.cloud().size([width, height])
            .words(d3.zip(vis_words, vis_freq).map(function(d) {
                                    return {text: d[0], size: wordScale(d[1]) };
                                    }))
            .padding(1)
            .rotate(function() { return ~~(Math.random() * 2) * 0; })
            .font("times")
            .fontSize(function(d) { return d.size; })
            .on("end", draw)
            .start();

    function draw(words) {
            d3.select(curr_id).append("svg")
                    .attr("width", width)
                    .attr("height", height)
                    .append("g")
                    .attr("transform", "translate(" + width/2 + "," +  height/2 + ")")
                    .selectAll("text")
                    .data(words)
                    .enter()
                    .append("text")
                    .transition()
                    .delay(function(d,i){
                                    return i*100;
                                    })
                    .duration(1000)
                    .ease("elastic")
                    .style("font-size", function(d) { return d.size + "px"; })
                    .style("font-family", "times")
                    .style("fill", function(d, i) { return fill(i); })
                    .attr("text-anchor", "middle")
                    .attr("transform", function(d) {
                                    return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
                                    })
                    .text(function(d) { return d.text; });
    }

I have a time slider to select a specific value, based on which words in the word cloud have different frequency(given by size) or some of the words are not there at all. I need to update without redrawing the entire word cloud which I am currently doing. In a way, I want to keep the position of words fixed and just updating their size and whether they exist based on the value selected on a slider?

Should I enter an update function in the function draw for this? Am certainly new to D3 and any help would be great?


Solution

  • To do this, you would select the existing text elements and set the font-size property for them. The code to do this looks like this:

    d3.select("svg").selectAll("text")
      .style("font-size", function(d, i) { // do something });