我正在尝试创建部分填充的圆圈,就像最终纽约时报政治大会可视化中的圆圈:http://www.nytimes.com/interactive/2012/09/06/us/politics/convention-word-counts.html
我为 d3 中的剪辑路径找到的两个最清晰的代码示例(https://gist.github.com/1067636 和 http://bl.ocks.org/3422480)为每个剪辑路径创建具有唯一 ID 的单独 div 元素,然后将这些路径应用于单个元素。
我不知道如何从这些示例转到基于数据值为一组元素中的每个元素使用唯一的圆形 clipPath 的可视化,以便我可以创建我的效果。
这是我到目前为止:
给定具有以下结构的数据:
data = [
{value: 500, pctFull: 0.20, name: "20%"},
{value: 250, pctFull: 0.75, name: "75%"},
{value: 700, pctFull: 0.50, name: "50%"},
]
1) 为数据集中的每个对象创建一个带有圆圈的力图。圆的面积由对象值导出。
2) 使用 mbostock 示例中的算法从每个数据点的比例 (pctFull) 计算 k(和 h)http://bl.ocks.org/3422480
3) 使用 k 为覆盖圆适当区域的每个数据点生成一个矩形。
如果我可以将每个矩形的可见性限制在其各自的圆圈内,我认为该插图就可以完成,但这是我被困的地方。我尝试了很多东西,但都没有用。
这是 jsfilddle:http://jsfiddle.net/G8YxU/2/
最佳答案
在这里查看工作 fiddle :http://jsfiddle.net/nrabinowitz/79yry/
// blue circle
node.append("circle")
.attr("r", function(d, i) {return rVals[i];})
.style("fill", "#80dabe")
.style("stroke", "#1a4876");
// clip path for the brown circle
node.append("clipPath")
// make an id unique to this node
.attr('id', function(d) { return "clip" + d.index })
// use the rectangle to specify the clip path itself
.append('rect')
.attr("x", function(d, i){ return rVals[i] * (-1);})
.attr("width", function(d, i){ return rVals[i] * 2;})
.attr("y", function(d, i) {return rVals[i] - (2 * rVals[i] * kVals[i]);})
.attr("height", function(d, i) {return 2 * rVals[i] * kVals[i];});
// brown circle
node.append("circle")
// clip with the node-specific clip path
.attr("clip-path", function(d) { return "url(#clip" + d.index + ")"})
.attr("r", function(d, i) {return rVals[i];})
.style("fill", "#dabe80")
.style("stroke", "#1a4876");
看起来为元素指定剪辑路径的唯一方法是使用
url(IRI)
clip-path
中的符号属性,这意味着您需要一个基于节点数据的每个剪辑路径的唯一 ID。我使用了clip<node index>
表格对于 id - 所以每个节点都有自己的剪辑路径,节点的其他子元素可以引用它。按照 Mike 的示例,制作两个不同颜色的圆并使用矩形本身作为剪辑路径,而不是制作基于圆的剪辑路径,这似乎是最简单的。但您可以采用任何一种方式。
关于javascript - 为 d3.js 中的多个元素生成 clipPaths,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12390158/