我试图在scaleBand上使用rescaleX将缩放功能添加到分组条形图。
var x0 = d3.scaleBand()
.rangeRound([0, width])
.paddingInner(0.1);
var x1 = d3.scaleBand()
.padding(0.05);
var zoom = d3.zoom()
.scaleExtent([1, 8])
.translateExtent([[0, 0], [width, height]])
.extent([[0, 0], [width, height]])
.on("zoom", () => { zoomed() });
...
function zoomed() {
var t = d3.event.transform;
var x0t = t.rescaleX(this.x0);
var x1t = t.rescaleX(this.x1);
...
}
但t.rescaleX(this.x0)
无法在scaleBand上工作,如何将缩放功能应用于scaleBand?
这是一个完整的代码集Grouped Bar Chart
答案 0 :(得分:3)
我能够通过将缩放功能更改为:
来实现此目的function zoomed() {
var t = d3.event.transform;
// redefine the x0 domain range with the event transform scale (k)
x0.range([0, width * t.k]);
// transform .barGroup using redefined domain range and event transform params
g.selectAll(".barGroup")
.attr("transform", function(d) { return "translate(" + (x0(d.State) + t.x) + ",0)scale(" + t.k + ",1)"; });
// apply transform to .axis--x and call xAxis
g.select(".axis--x")
.attr("transform", "translate(" + t.x + "," + (height) + ")")
.call(xAxis);
}
完整码本here
<强>更新强> Mike Bostock缩放scaleBand条形图的更好方法(非分组) https://beta.observablehq.com/@mbostock/d3-zoomable-bar-chart
更新2: 更新了分组条形图缩放功能:
function zoomed() {
x0.range([0, width].map(d => d3.event.transform.applyX(d)));
x1.rangeRound([0, x0.bandwidth()]);
g.selectAll(".barGroup").attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; });
g.selectAll(".bar").attr("x", function(d) { return x1(d.key); }).attr("width", x1.bandwidth());
g.select(".axis--x").call(xAxis);
}
完整的Codepen:here