私はこのようなデータ構造を持っています(データ構造が交渉不可能であると仮定します):
data = {
segments : [
{x : 20, size : 10, colors : ['#ff0000','#00ff00']},
{x : 40, size : 20, colors : ['#0000ff','#000000']}
]};
d3.js javascriptライブラリを使用して、両方のcolors
配列の各色に1つずつ、合計4つの長方形を描画したいと思います。配列の各エントリからの情報は、segments
配列の各色に対応する長方形を描画するために使用されcolor
ます。たとえば、赤と緑の長方形の幅と高さは10になります。結果のhtmlは次のようになります。
<div id="container">
<svg width="200" height="200">
<g>
<rect x="20" y="20" width="10" height="10" fill="#ff0000"></rect>
<rect x="30" y="30" width="10" height="10" fill="#00ff00"></rect>
</g>
<g>
<rect x="40" y="40" width="20" height="20" fill="#0000ff"></rect>
<rect x="60" y="60" width="20" height="20" fill="#000000"></rect>
</g>
</svg>
</div>
私はこれを達成するいくつかのコードを思いついたが、2つの異なるレベルのネストからのデータを使用することについての部分data
が混乱していることに気づき、d3.jsで同じことを達成するためのより慣用的な方法があるかもしれないと感じています。コードは次のとおりです( http://jsbin.com/welcome/39650/editの完全な例):
function pos(d,i) { return d.x + (i * d.size); } // rect position
function size(d,i) { return d.size; } // rect size
function f(d,i) { return d.color; } // rect color
// add the top-level svg element and size it
vis = d3
.select('#container')
.append('svg')
.attr('width',200)
.attr('height',200);
// add the nested svg elements
var nested = vis
.selectAll('g')
.data(data.segments)
.enter()
.append('g');
// Add a rectangle for each color
nested
.selectAll('rect')
.data(function(d) {
// **** ATTENTION ****
// Is there a more idiomatic, d3-ish way to approach this?
var expanded = [];
for(var i = 0; i < d.colors.length; i++) {
expanded.push({
color : d.colors[i],
x : d.x
size : d.size });
}
return expanded;
})
.enter()
.append('rect')
.attr('x',pos)
.attr('y',pos)
.attr('width',size)
.attr('height',size)
.attr('fill',f);
d3.jsを使用して、データ構造内の2つの異なるレベルのネストからデータにアクセスするためのより良いおよび/またはより慣用的な方法はありますか?
編集
クロージャのアイデアに対するmeetamitの回答のおかげで、私が思いついた解決策は次のとおりです。また、nautatの回答のおかげでより慣用的なd3.jsインデントを使用しています。
$(function() {
var
vis = null,
width = 200,
height = 200,
data = {
segments : [
{x : 20, y : 0, size : 10, colors : ['#ff0000','#00ff00']},
{x : 40, y : 0, size : 20, colors : ['#0000ff','#000000']}
]
};
// set the color
function f(d,i) {return d;}
// set the position
function pos(segment) {
return function(d,i) {
return segment.x + (i * segment.size);
};
}
// set the size
function size(segment) {
return function() {
return segment.size;
};
}
// add the top-level svg element and size it
vis = d3.select('#container').append('svg')
.attr('width',width)
.attr('height',height);
// add the nested svg elements
var nested = vis
.selectAll('g')
.data(data.segments)
.enter().append('g');
// Add a rectangle for each color. Size of rectangles is determined
// by the "parent" data object.
nested
.each(function(segment, i) {
var
ps = pos(segment),
sz = size(segment);
var colors = d3.select(this)
.selectAll('rect')
.data(segment.colors)
.enter().append('rect')
.attr('x', ps)
.attr('y',ps)
.attr('width', sz)
.attr('height',sz)
.attr('fill', f);
});
});
完全に機能する例は次のとおりです。http://jsbin.com/welcome/42885/edit