我尝试在D3 svg中添加不同的形状大小标记(例如,三角形,矩形,圆形), 例如,如果级别为admin,则标记形状为圆形 如果level是成员,则标记形状为三角形 如果level为guest,则标记形状为矩形 我尝试使用gooup.each
var groups = svg
.style("overflow", "visible")
.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function(d) {return "translate(" + projection([d.lon,d.lat])+ ")";});
groups.each(function(d) {
var elem = d3.select(this);
if (d.level == "admin") {
elem.append("rect").attr("width", 5).attr("height", 5)
.style("fill",function() {
return "red";
});
}
if (d.level == "member") {
elem.append("path").attr("d", 'M 100 100 L 300 100 L 200 300 z').attr('transform','scale(0.04) translate(-150,-130)')
.style("fill",function() {
return "green";
});
}
if (d.level == "guest") {
elem.append("circle").attr("r", 4).attr('cy',2).attr('cx',2)
.style("fill",function() {return "yellow";});
}
});
但它无法显示数据数组中的第一个数据,
来自my code的,正如您所看到的,它无法显示数据数组中的第一个数据,但我不确定如何修改。我真的很感谢你的帮助!
答案 0 :(得分:0)
您可以将组g
- 元素附加到svg,遍历这些组并为其添加不同的形状
看一下片段
<div id='graphContent'></div>
<script src='https://d3js.org/d3.v4.min.js'></script>
<script>
var selector = "#graphContent";
var data = [{ level: "admin" }, { level: "admin" },{ level: "member" }, { level: "guest" },{ level: "admin" }];
var groups = d3
.select("#graphContent")
.append("svg")
.style("overflow", "visible")
.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", (d, i) => `translate(0,${i * 20})`);
groups.each(function(d) {
var elem = d3.select(this);
if (d.level == "admin") {
//rectangle
elem.append("rect").attr("width", 5).attr("height", 5);
}
if (d.level == "member") {
//triangle
//svg does not have triangle shape , so we use path to draw it
elem.append("path").attr("d", 'M 100 100 L 300 100 L 200 300 z').attr('transform','scale(0.04) translate(-150,-130)')
}
if (d.level == "guest") {
//circle
elem.append("circle").attr("r", 4).attr('cy',2).attr('cx',2);
}
});
</script>