Adorabelle Atticus
Adorabelle Atticus

Reputation: 11

How can I draw circles for two different columns in d3 v5?

I want to create a scatterplot of my data which consists of three columns of Year, Men and Women. I want to draw circles for both Men and Women columns that correspond to the year. Here's the code I've written, but only the first set of circles are added to the SVG. I'm using d3 v5.

svg.selectAll("circle")
                .data(dataset)
                .enter()
                .append("circle")
                .attr("cx", d => xScale(d.Year))
                .attr("cy", d => yScale(d.Men))
                .attr("r", d => aScale(d.Men))
                .attr("id", "men")
                .attr("fill", function(d) {
                    return "rgb(0, 0, " + Math.round((d.Men) * 20) + ")"
                });

                svg.selectAll("circle")
                .data(dataset)
                .enter()
                .append("circle")
                .attr("cx", d => xScale(d.Year))
                .attr("cy", d => yScale(d.Women))
                .attr("r", d => aScale(d.Women))
                .attr("id", "women")
                .attr("fill", "green");

Upvotes: 0

Views: 438

Answers (1)

Alan Grosz
Alan Grosz

Reputation: 1325

You are using wrong the enter() method. The enter evaluates witch data is newer, using the selector before. In your case, the selector is circle. Like you are using again the same selector, data and enter for the second case, the enter doesn't detect new changes. Your must to store the enter in a variable and use it for both:

const circleEnter = svg.selectAll("circle")
            .data(dataset)
            .enter();

circleEnter.append("circle")
            .attr("cx", d => xScale(d.Year))
            .attr("cy", d => yScale(d.Men))
            .attr("r", d => aScale(d.Men))
            .attr("id", "men")
            .attr("fill", function(d) {
                return "rgb(0, 0, " + Math.round((d.Men) * 20) + ")"
            });

circleEnter.append("circle")
            .attr("cx", d => xScale(d.Year))
            .attr("cy", d => yScale(d.Women))
            .attr("r", d => aScale(d.Women))
            .attr("id", "women")
            .attr("fill", "green");

Good luck!

Upvotes: 1

Related Questions