这是我的jsfiddle,它显示了2个piecharts这让我在HTML视图中得到了这样的东西:
<svg width="220" height="220">
<svg width="220" height="220">
这是我的小提琴,我试图在2个皮图之前插入svg,但我没有正确地写,1个饼状图得到了写。
谁能告诉我怎么才能让所有3个svg显示?
我所有的代码都在第二提琴
var width = $(document).width()-50 || 960,
height = $(document).height()-50 ||500;
//attaches/appends a svg tag to a body tag with a width and height
/* COMMENT IN */
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
data=[[10, 5],[32, 24]]
z = d3.scale.category20c();
//attaches/appends a svg tag to a body tag with a width and height
var svg2 = d3.select("body").selectAll("svg")
.data(data)
.enter().append("svg:svg")
.attr("width", 220)
.attr("height", 220)
.append("svg:g")
.attr("transform", "translate(" + 100 + "," + 100 + ")")
svg2.selectAll("path")
.data(d3.layout.pie())
.enter().append("svg:path")
.attr("d", d3.svg.arc()
.innerRadius(10)
.outerRadius(100))
.style("fill", function(d, i) { return z(i); });
注意:进一步的背景是,第一个svg是我正在工作的地图。我要做的是在这个图层上新建一个图层,在这个例子中是2个,但你必须从某个地方开始:)
你对结果的解释有点错误。第一个饼状图不会被覆盖,它首先不会被渲染。在注释的版本中,您正在为您的地图添加svg,它工作得很好,可以很容易地通过分配给它的width
和height
值来识别。
当尝试为饼状图添加svg时,您通过执行d3.select("body").selectAll("svg")
选择了主体中的所有svg。这个选择将包括前面附加的SVG。然后将数据绑定到将计算数据连接的选择。由于绑定的是一个没有任何键函数的数据数组,因此连接将基于索引。因此,现有的SVG将对应于数据数组中的第一个元素,并将被放入更新选项中。由于您的代码只适用于输入选择,因此将永远不会绘制第一个饼状图,因为它不属于此选择。第二个将按预期输出。
var svg2 = d3.select("body").selectAll("svg.pie") // select with class "pie"
.data(data)
.enter().append("svg:svg")
.attr("width", 220)
.attr("height", 220)
.classed("pie", true) // set marker class for all pie charts
.append("svg:g")
.attr("transform", "translate(" + 100 + "," + 100 + ")")
因为不存在具有pie
类的SVG,所以您的所有数据最终将在输入选项中呈现包含每个数据元素的饼状图的SVG。我已经更新了你的JSFiddle来显示效果。