【发布时间】:2016-12-29 03:08:35
【问题描述】:
编辑:JSBin 不工作去JS fiddle 看我的代码
我正在使用 d3 和 crossfilter 训练自己,但我遇到了一些困难。
我正在尝试创建一个链接函数来创建条形图。 我们的想法是不要为我要创建的每个条形图一次又一次地编写所有代码。
我受到示例 Fast Multidimensional Filtering for Coordinated Views 的启发,这是我想做的(你可以找到代码 Here)。
但我想在我的通用 barChart 函数中加入一些个人风格。
我决定使用示例中的链接函数来实现。
我知道如何根据需要创建尽可能多的图形,但我不明白,(当出现画笔事件时),如何根据过滤器重绘所有栏。
如果我想在函数之外执行此操作,我将再次定义所有属性,如 x、y、轴等,具体取决于新数据,即过滤后的数据,如下所示:
var updateRange = function(filt){
data = dimension.filter(filt) //assuming dimension is a crossfilter dimension
// Scale the range of the data again
x.domain([0, d3.max(data, function(d) { return d.key; })+1]);
// Select the section we want to apply our changes to
var chart = d3.select(".chart")
//Update all rects
chart.selectAll("rect.hidden")
.data(data)
.transition()
.delay(function(d, i) {
return i * 50;
})
.duration(500)
.attr("y", function(d) {
return y2(d.value);
})
.attr("height", function(d) {
return height - y2(d.value);
});
我发了一个JSBin 来讨论我们如何更新图表。
这就是我使用的brush 函数。
brush.on("brushstart", function() {
var div = d3.select(this.parentNode.parentNode.parentNode);
div.select(".title a").style("display", null);
});
brush.on("brush", function() {
var g = d3.select(this.parentNode),
extent = brush.extent();
if (round) g.select(".brush")
.call(brush.extent(extent = extent.map(round)))
.selectAll(".resize")
.style("display", null);
g.select("#clip-" + id + " rect")
.attr("x", x(extent[0]))
.attr("width", x(extent[1]) - x(extent[0]));
dimension.filter(extent);
});
brush.on("brushend", function() {
if (brush.empty()) {
var div = d3.select(this.parentNode.parentNode.parentNode);
div.select(".title a").style("display", "none");
div.select("#clip-" + id + " rect").attr("x", null).attr("width", width);
dimension.filterAll();
}
)};
等待你的cmets,
克里斯。
编辑:一些澄清
为了更清楚,当我渲染图表并使用画笔时,数据被正确过滤。 (如果我放一些 console.log,我会看到根据画笔过滤的数据)
但是图表不会根据刷子更新。我知道问题来自我使用画笔事件的方式 (brush.on()。
我想我需要以某种方式调用渲染函数,但不知道如何将链接函数应用于所有图表。
编辑:使用外部画笔更新图表
现在在外部设置画笔时(通过单击链接)成功更新图表。
只需添加这行
if (brushDirty) {
brushDirty = false;
g.selectAll(".brush").call(brush);
div.select(".title a").style("display", brush.empty() ? "none" : null);
if (brush.empty()) {
g.selectAll("#clip-" + id + " rect")
.attr("x", 0)
.attr("width", width);
} else {
var extent = brush.extent();
g.selectAll("#clip-" + id + " rect")
.attr("x", x(extent[0]))
.attr("width", x(extent[1]) - x(extent[0]));
}
}
【问题讨论】:
标签: javascript d3.js crossfilter method-chaining brush