D3: Is it possible to zoom+pan one axis and only pan the other?

前端 未结 3 1771
北海茫月
北海茫月 2020-12-28 16:34

I have zoom and pan working for the x axis but I\'d like to add panning for the y axis. I tried using d3.behavior.zoom and d3.event.translate[1] to

3条回答
  •  天涯浪人
    2020-12-28 17:20

    JSFIDDLE: https://jsfiddle.net/sladav/o8vaecyn/

    For starters, the zoom behavior handles both pan and zoom for the x axis, and that's handled by...

    var zoom = d3.behavior.zoom()
        .x(x)
        .scaleExtent([1, 10])
        .on("zoom", zoomed);
    

    So we'll use zoom to handle the x axis stuff.

    FOR THE Y AXIS, to get JUST the pan behavior...

    Create a separate drag behavior that captures the "dy", shifts the y domain, and reapplies it.

    1. Add in a drag behavior

      var drag = d3.behavior.drag()
           .on("drag", dragging)
      
    2. Let the y scale's domain be variable (we'll modify that as we drag)

      var yPan = 0;
      var yMin = (-height / 2);
      var yMax = (height / 2);
      
      var y = d3.scale.linear()
          .domain([yMin, yMax])
          .range([height, 0]);
      
    3. Add a function to rescale the Y axis on the drag event

      function dragging(d) {
         yPan = d3.event.dy;
         yMin += yPan;
         yMax += yPan;
         y.domain([yMin, yMax])
         d3.select(".y.axis").call(yAxis)};
      
    4. Call the drag function from your SVG element

      var svg = d3.select("body").append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
          .append("g")
             .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
             .call(zoom)
             .call(drag);
      

提交回复
热议问题