我刚接触D3,正在尝试将一个D3 Treemap从V3版本转换到V4版本。我已经阅读了一些更新的信息,但无法让它正常工作。
这个Treemap来自于Pivottable.js D3渲染器。
这是相关的代码部分。
color = d3.scale.category10();
width = opts.d3.width();
height = opts.d3.height();
treemap = d3.layout.treemap().size([width, height]).sticky(true).value(function(d) {
return d.size;
});
d3.select(result[0]).append("div").style("position", "relative").style("width", width + "px").style("height", height + "px").datum(tree).selectAll(".node").data(treemap.padding([15, 0, 0, 0]).value(function(d) {
return d.value;
}).nodes).enter().append("div").attr("class", "node").style("background", function(d) {
if (d.children != null) {
return "lightgrey";
} else {
return color(d.name);
}
}).text(function(d) {
return d.name;
}).call(function() {
this.style("left", function(d) {
return d.x + "px";
}).style("top", function(d) {
return d.y + "px";
}).style("width", function(d) {
return Math.max(0, d.dx - 1) + "px";
}).style("height", function(d) {
return Math.max(0, d.dy - 1) + "px";
});
});
使用D3 V4时,我遇到了一些错误。
例如,“d3.scale.category10”不是一个函数。 我用“d3.scaleOrdinal(d3.schemeCategory10)”替换它。
然后出现了“sticky不是函数”的错误。 我用“tile(d3.treemapResquarify)”替换它。
但是我还是遇到了“value不是函数”和“enter不是函数”的问题,我无法解决。 而且我不确定是否需要改变其他东西才能使其与D3 V4配合工作。
这是我的代码。但是它不能正常工作。
// Updated to V4
color = d3.scaleOrdinal(d3.schemeCategory10);
width = opts.d3.width();
height = opts.d3.height();
// Updated sticky for V4
treemap = d3.treemap().size([width, height]).tile(d3.treemapResquarify).value(function(d) {
return d.size;
});
d3.select(result[0]).append("div").style("position", "relative").style("width", width + "px").style("height", height + "px").datum(tree).selectAll(".node").data(treemap.padding([15, 0, 0, 0]).value(function(d) {
return d.value;
}).nodes).enter().append("div").attr("class", "node").style("background", function(d) {
if (d.children != null) {
return "lightgrey";
} else {
return color(d.name);
}
}).text(function(d) {
return d.name;
}).call(function() {
this.style("left", function(d) {
return d.x + "px";
}).style("top", function(d) {
return d.y + "px";
}).style("width", function(d) {
return Math.max(0, d.dx - 1) + "px";
}).style("height", function(d) {
return Math.max(0, d.dy - 1) + "px";
});
});
有人可以帮我把这个剩余部分转化一下吗?
// 编辑 这是一个工作中的D3 v3示例fiddle。d3_renderer在JS部分中。 https://jsfiddle.net/qntc8e7w/
这里是相同的示例,但使用了D3 v4 https://jsfiddle.net/ybctz0a8/