在d3中缩放双缩放图表的左右轴

时间:2014-03-20 20:21:51

标签: javascript svg d3.js zooming

我有使用d3的双比例线图,coffescript在

之下
# bottom axis
xScale = d3.time.scale().range([0,width]).domain(d3.extent(data, (d) -> d.date))
xAxis = d3.svg.axis().scale(xScale).orient("bottom").ticks(5)
# left axis
yLeftMax = d3.max(data, (d) -> d.price)
yLeftScale = d3.scale.linear().domain([0, yLeftMax]).range([height, 0])
yLeftAxis = d3.svg.axis().scale(yLeftScale).orient("left")
# right axis
yRightMax = d3.max(data, (d) -> d.yoy)
yRightMin = d3.min(data, (d) -> d.yoy)
yRightAbsMax = Math.max(Math.abs(yRightMin), Math.abs(yRightMax))
yRightScale = d3.scale.linear().domain([-yRightAbsMax, yRightAbsMax]).range([height, 0])
yRightAxis = d3.svg.axis().scale(yRightScale).orient("right")
myZoom = ->
  canvas.select("._x._axis").call xAxis
  #canvas.select(".axisLeft").call yLeftAxis  // can't zoom left axis here
  canvas.select(".axisRight").call yRightAxis // Zoom right axis
  canvas.select(".line1").attr("d", line1(data)) // Zoom left scaled line
  canvas.select(".line2").attr("d", line2(data)) // Zoom right scaled line
zoom = d3.behavior.zoom()
 .x(xScale) // set xScale for zoom 
 #.y(yLeftScale) // can't set left yScale for zoom here
 .y(yRightScale) // set right yScale for zoom  
 .scaleExtent([1,20]) # 20x times zoom
 .on("zoom", myZoom)
...

问题是,当我使用变焦时,左右y轴都会被缩放,即我无法对两个y刻度进行变焦工作。

1 个答案:

答案 0 :(得分:3)

myZoom功能中,您可以明确设置domain的{​​{1}}:

yLeftScale

备用解决方案是具有两个单独的缩放行为并控制其他myZoom = -> scale = d3.event.scale translate = d3.event.translate # Haven't verified these calculations. Is it scale first or translate first? # See `alternate answer` below for a better approach yLeftScale.domain([0 + translate[1], yLeftMax / scale + translate[1]) canvas.select("._x._axis").call xAxis canvas.select(".axisLeft").call yLeftAxis # can't zoom left axis here canvas.select(".axisRight").call yRightAxis # Zoom right axis canvas.select(".line1").attr("d", line1(data)) # Zoom left scaled line canvas.select(".line2").attr("d", line2(data)) # Zoom right scaled line 行为,而不是手动更新zoom。我发现这更加强大,虽然有点冗长。

domains

并在zoomLeft = d3.behavior.zoom() .x(xScale) # set xScale for zoom .y(yLeftScale) # can't set left yScale for zoom here .scaleExtent([1,20]) # 20x times zoom 中设置myZoom的{​​{1}}和zoomLeft

scale