d3 - removing elements from updated word cloud

62 views
Skip to first unread message

Andrzej

unread,
Feb 22, 2019, 7:51:27 AM2/22/19
to d3-js

I've modified this block, so based on dropdown selection my word cloud is modified. It works but the only problem is that when I update it the old elements are still visible. I reckon I should remove them first with exit().remove() but it's a new thing for me and I don't know how I can do it. I'm totally lost


The cata looks like this:


 {"all": [{"key": "word1", "value": 432}, {"key": "word2", "value": 384}], 
    "first": [{"key": "word3", "value": 432}, {"key": "word4", "value": 384}], 
    "second": [{"key": "word5", "value": 55}, {"key": "word6", "value": 54}]}



My code:


d3.json("data/data.txt",function(data){

        var color = d3.scaleOrdinal(d3.schemeCategory20);
        update(data['all']);
        d3.select("#inds")
            .on("change", function(d) {
                index = this.value;
                console.log(data[index]);
                update(data[index]);
            })

        function draw(words) {
            var wordcloud = g.append("g")
                .attr('class','wordcloud')
                .attr("transform", "translate(" + width/2 + "," + height/2 + ")");

            wordcloud.selectAll("text")
                .data(words)

                .enter().append("text")
                    .attr('class','word')
                    .style("fill", function(d, i) { return color(i); })
                    .style("font-size", function(d) { return d.size + "px"; })
                    .style("font-family", function(d) { return d.font; })
                    .attr("text-anchor", "middle")
                    .attr("transform", function(d) {
                        return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
                    })
                    .text(function(d) { return d.text; });

        };

        function update(x){

            var max = d3.max(Object.keys(x), function(k){
                return x[k].value;
            });

            var font_size = d3.scaleLinear()
                .domain([1, max])
                .range([10,100]);



            var layout = d3.layout.cloud()
                .size([width, height])
                .timeInterval(20)
                .words(x)
                .rotate(function() { return ~~(Math.random() * 2) * 90; })
                .fontSize(function(d) { return font_size(d.value); })
                .fontWeight(["bold"])
                .text(function(d) { return d.key; })
                .on("end", draw)
                .start();


        }

    });
Reply all
Reply to author
Forward
0 new messages