如何在d3v5中为两个不同的列绘制圆



我想创建一个数据散点图,由Year、Men和Women三列组成。我想为"男性"one_answers"女性"列画与年份对应的圆圈。这是我编写的代码,但SVG中只添加了第一组圆圈。我使用的是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");

您使用了错误的enter((方法。输入评估开关数据较新,之前使用选择器。在您的情况下,选择器是圆形的。就像在第二种情况下再次使用相同的选择器、数据和回车一样,回车不会检测到新的更改。您必须将输入存储在变量中,并将其用于两者:

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");

祝你好运!

最新更新