我试图让 d3 迭代数据中的子数组并生成多个饼图。
这是完整的代码(来自https://gist.github.com/mbostock/1305111 https://gist.github.com/mbostock/1305111
and https://gist.github.com/enjalot/1203641 https://gist.github.com/enjalot/1203641):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3 Page Test</title>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<style type="text/css">
body {
text-align: center;
}
</style>
</head>
<body>
<script type="text/javascript">
// Define the data as a two-dimensional array of numbers. If you had other
// data to associate with each number, replace each number with an object, e.g.,
// `{key: "value"}`.
var datad = [
{s:[ 20, 1, 1], l:[10,100]},
{s:[ 1, 20, 1], l:[ 20, 200]},
{s:[ 1, 1, 20], l:[ 30,300 ]}
];
// Define the margin, radius, and color scale. The color scale will be
// assigned by index, but if you define your data using objects, you could pass
// in a named field from the data object instead, such as `d.name`. Colors
// are assigned lazily, so if you want deterministic behavior, define a domain
// for the color scale.
var m = 10,
r = 100,
z = d3.scale.category20c();
// Insert an svg:svg element (with margin) for each row in our dataset. A
// child svg:g element translates the origin to the pie center.
var svg = d3.select("body").selectAll("svg")
.data([datad])
.enter().append("svg:svg")
.attr("width", (r + m) * 2)
.attr("height", (r + m) * 2)
.append("svg:g")
.attr("transform", "translate(" + (r + m) + "," + (r + m) + ")");
var pie = d3.layout.pie() //this will create arc data for us given a list of values
.value(function(d, i) { return d.s[i]; }); //we must tell it out to access the value of each element in our data array
// The data for each svg:svg element is a row of numbers (an array). We pass
// that to d3.layout.pie to compute the angles for each arc. These start and end
// angles are passed to d3.svg.arc to draw arcs! Note that the arc radius is
// specified on the arc, not the layout.
svg.selectAll("path")
.data(pie)
.enter().append("svg:path")
.attr("d", d3.svg.arc()
.innerRadius(0)
.outerRadius(r + 2))
.style("fill", function(d, i) { return z(i); });
</script>
</body>
</html>
我得到一个饼图,它由数据集中每个“s”数组中的“20”值组成。
第一个饼图是从 data[0][0] 中绘制的,第二个饼图是从 dated[1][1] 中绘制的,第三个饼图是从 datad[2][2] 中绘制的。
我期待三个饼图(数据中的每个“s”数组一个)。
我认为我的问题在于:
var pie = d3.layout.pie() //this will create arc data for us given a list of values
.value(function(d, i) { return d.s[i]; }); //we must tell it out to access the value of each element in our data array
我如何告诉它迭代每个 s 数组,而不是同时迭代 datad 和 s 数组。也就是说,我想迭代 datad[0]s[0], datad[0]s[1], datad[0]s[2] ... datad[2]s[0], datad[2]s [1](等)而不是 datad[0]s[0]、datad[1]s[1]、datad[2]s[2]
提示或指示表示赞赏!
编辑:这是小提琴:jsfiddle.net/H2SKt/701/