在D3.js中结合对象定位和标签
问题描述:
我是D3js的新手,并且(可能愚蠢地)正在探索其作为简单导航工具的价值。 I have managed to cobble together a basic page that works,但它似乎相当详细,我想知道是否有人有任何指示它可能会被重写为更优雅,并可能集成标签和圆形绘图功能?在D3.js中结合对象定位和标签
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<script type="text/javascript" src="scripts/d3.v3.js"></script>
</head>
<body>
<div id="viz"></div>
<div id="status" style="position:fixed;bottom:0;left:0;
color:white;background-color:grey;font-size:small"></div>
<script type="text/javascript">
// functions for adding a 'status' box with link info
function addStatus(targetURL){document.getElementById('status').innerHTML=targetURL;}
function clearStatus(){document.getElementById('status').innerHTML=null;}
var sampleSVG = d3.select("#viz")
.append("svg")
.attr("width", 500)
.attr("height", 200);
var dataset = [[100, 100, "http://google.com/", "Google"],
[300, 100, "http://yahoo.com/", "Yahoo"]];
// Add labels
sampleSVG.selectAll("text")
.data(dataset)
.enter().append("text")
.attr("text-anchor", "middle")
.attr("x", function(d){return d[0]})
.attr("y", function(d){return d[1]})
.text(function(d) {return d[3];});
// Add circles and functionality
sampleSVG.selectAll("circle")
.data(dataset)
.enter().append("circle")
.style("fill", "transparent")
.style("stroke", "grey")
.style("stroke-width", 3)
.attr("r", 50)
.attr("cx", function(d){return d[0]})
.attr("cy", function(d){return d[1]})
.on("mouseover",
function(d){ d3.select(this).style("stroke", "black");
addStatus(d[2]); }
)
.on("mouseout",
function(){
d3.select(this).style("stroke", "grey");
clearStatus(); })
.on("mouseup", function(d){window.location = d[2];});
</script>
<!-- ... -->
</body>
</html>
答
如果每个圆圈有一个标签,则可以将两个呼叫组合起来选择圆圈和文本。也就是说,在同一个选择上添加圆圈和标签。
var sel = sampleSVG.selectAll("text")
.data(dataset)
.enter();
sel.append("text")
...
sel.append("circle")
...
你甚至可以在一个调用链中做所有事情。
sampleSVG.selectAll("text")
.data(dataset)
.enter()
.append("circle")
...
.append("text");
这将追加text
元素到circle
元素,但并不能(相对于事件处理程序尤其是)可以产生在所有情况下都想要的结果。
除此之外,d3不提供任何功能来同时放置两个形状和标签。有一些库为NVD3提供了功能。
编写自己的包装函数可能是最容易的,在给定数据的情况下,可以按照需要添加形状和标签。
下面是一个工作示例:http://bl.ocks.org/AndrewStaroscik/5223431 – 2013-03-22 18:15:16
热销bl.ocks!感谢chaps。 – geotheory 2013-03-22 19:04:29