条形放大 d3.js

Bars zoom on d3.js

我想使用 d3.js 制作一个垂直缩放柱状图的图表。我做错了,因为结果不是我想要的。

这是我的缩放:

   svg.selectAll('g.info-group').each(function (d, i) {
          var el = d3.select(this);

          svg.select('.bars').attr('transform', 'translate(0,' + d3.event.translate[1] + ')');

          el
           .selectAll('.bar')
           .call(function (s) {
              barSetPosition(s, d.ib, i);
           });
       });

       svg.select('.y.axis').call(yAxis);

这是一个jsFiddle

什么不起作用:

  1. y 轴可能有负值,在值不存在的地方非常正。
  2. 如果我滚动条形图和 y 轴不一致。

我该如何纠正?

更新 (05.19.2015): 我找到了这个问题的解决方案,这里是 - jsFiddle

 var zoom = d3.behavior.zoom()
    .y(yScale)
    .scaleExtent([1, 2])
    .on("zoom", function () {
       var t = zoom.translate(),
        tx = t[0],
        ty = t[1],
        scale = zoom.scale();

       ty = Math.min(ty, 0);

       ty = Math.max(ty, canvasH + margin.top - (canvasH + margin.top) * scale);

       zoom.translate([tx, ty]);

       svg
        .select('.bars')
        .attr("transform", "translate(0," + ty + ")");

       svg.selectAll('.bar')
        .attr('y', function (d) {
           return (canvasH + margin.top) * scale - (yScale(0) - yScale(d.ib));
        })
        .attr('height', function (d) {
           return yScale(0) - yScale(d.ib);
        })
        .attr('width', barScale.rangeBand());

       svg.select('.y.axis').call(yAxis);
    });

现在缩放工作正常。

但是现在还有两个问题。

  1. 当我进行缩放和平移到下方时,条形图位于 X 轴下方,轴上的数字被隐藏。
  2. 当我悬停条形图缩放时,平移到下方条形图会颤抖。

如何解决这个问题?谢谢。

我解决了所有问题,最终代码是 - jsFiddle

这是主要部分:

var zoom = d3.behavior.zoom()
    .y(yScale)
    .scaleExtent([1, 2])
    .on("zoom", function () {
       var t = zoom.translate(),
        tx = t[0],
        ty = t[1],
        scale = zoom.scale();

       ty = Math.min(ty, 0);

       ty = Math.max(ty, canvasH + margin.top - (canvasH + margin.top) * scale);

       zoom.translate([tx, ty]);

       svg
        .select('.bars')
        .attr("transform", "translate(0," + ty + ")");

       svg.selectAll('.bar')
        .attr('y', function (d) {
           return (canvasH + margin.top) * scale - (yScale(0) - yScale(d.ib));
        })
        .attr('height', function (d) {
           var height = (yScale(0) - yScale(d.ib)) - (canvasH + margin.top) * (scale - 1) - ty;

           if (height < 0) {
              height = 0;
           }

           return height;
        })
        .attr('width', barScale.rangeBand());

       svg.select('.y.axis').call(yAxis);
    });

   svg.call(zoom);