我想为每个数据点绘制一个矩形,如果某个值为true,还会在每个矩形的中心绘制一个点。虽然我可以用琐碎的方式绘制另一套点。但我希望在绘制相应的点时访问(父)矩形的某些属性(例如,x,y)。我在附图中说明了。你能帮帮我吗?谢谢。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title> Icon </title>
<script type="text/javascript" src="lib/d3/d3.v3.js"></script>
</head>
<body>
<p id="icon">
<script>
var dataset = [
{"id": 1, "selection": true},
{"id": 2, "selection": true},
{"id": 3, "selection": true},
{"id": 4, "selection": false},
{"id": 5, "selection": false},
{"id": 6, "selection": true},
{"id": 7, "selection": false},
{"id": 8, "selection": true}
];
var svg = d3.select("#icon")
.append("svg")
.attr("height", 200)
.attr("width", 200);
var x = 10, y = 10;
svg.selectAll("rect")
.data(dataset).enter()
.append("rect")
.attr("width", 10)
.attr("height", 10)
.attr("x", function(d, i) { return x = x + 12; })
.attr("y", function(d, i) { return y; })
.style("fill", "yellow")
.style("stroke", "grey")
.style("stroke-width", ".5px");
</script>
</body>
</html>
答案 0 :(得分:1)
您可以使用与矩形相同的代码在顶部添加圆圈:http://jsfiddle.net/bh50q7Le/
只需使用一个函数设置笔划的样式,如果该点不是选择,则返回“无”。
格式化代码(我还参数化了矩形的大小):
var dataset = [
{"id": 1, "selection": true},
{"id": 2, "selection": true},
{"id": 3, "selection": true},
{"id": 4, "selection": false},
{"id": 5, "selection": false},
{"id": 6, "selection": true},
{"id": 7, "selection": false},
{"id": 8, "selection": true}
];
var rectsize = 30;
var svg = d3.select("#icon")
.append("svg")
.attr("height", rectsize*dataset.length)
.attr("width", rectsize*(dataset.length + 1));
svg.selectAll("rect")
.data(dataset).enter()
.append("rect")
.attr("width", rectsize)
.attr("height", rectsize)
.attr("x", function(d, i) { return i*(rectsize + 2); })
.attr("y", function(d, i) { return rectsize; })
.style("fill", "yellow")
.style("stroke", "grey")
.style("stroke-width", ".5px");
svg.selectAll("circle")
.data(dataset).enter()
.append("circle")
.attr("r", rectsize/4)
.attr("cx", function(d, i) { return rectsize*0.5 + i*(rectsize + 2); })
.attr("cy", function(d, i) { return rectsize*1.5; })
// color if selected
.style("stroke", function(d) { return d.selection ? "grey" : "none"})
.style("fill", "none")
.style("stroke-width", "2px");