Javascript D3选择<;g>;元素并修改填充
我用D3制作了一张美国地图,并填充了颜色Javascript D3选择<;g>;元素并修改填充,javascript,d3.js,Javascript,D3.js,我用D3制作了一张美国地图,并填充了颜色 var map = d3.select("#map").append("svg") .attr("width", svgWidth) .attr("height", svgHeight); d3.json("us.json", function (error, us) { map.append("g") .selectAll("p
var map = d3.select("#map").append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight);
d3.json("us.json", function (error, us) {
map.append("g")
.selectAll("path")
.data(topojson.feature(us, us.objects.states).features)
.enter().append("path")
.attr("d", path)
.style("stroke", function (d) { return "#000000"; } )
.style("fill", function (d) { return gradient(Math.random()); } )
};
现在,我想更改每个状态的颜色,但不是删除贴图然后重新添加,而是转换颜色
我试过:
d3.selectAll("#map").selectAll("g").selectAll("path")
但是,尝试循环这个数组的元素并没有帮助
我做错了什么
编辑:
我用来尝试更改每个状态(每个路径变量)的颜色的代码是
我不认为问题与上面的代码有关——正是我试图使用的代码来选择路径/状态给我带来了麻烦
我也试过了
d3.selectAll("path").attr("fill", function (d) { ... });
但是,这也没有起到任何作用(正如拉尔斯在评论中所说的,因为我以前使用过“
风格”
,所以我必须再做一次[而不是像以前那样使用attr
)
像我那样选择数据(d3.selectAll(“路径”))是选择状态的正确方法。你能发布你用来更改颜色的代码吗?只是添加了一些东西…希望这是你想要的!如果你在需要再次使用它之前使用了
.style()
,例如d3.selectAll(“路径”).style(“fill”,函数(d){…};
。太简单了。谢谢。可能永远不会明白这一点。
d3.selectAll("path").attr("fill", function (d) { ... });