缩放左轴和右轴的双重缩放图表在d3

Zoom left and right axis for dual scaled chart in d3

本文关键字:缩放 d3      更新时间:2023-09-26

我有双缩放折线图使用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尺度

myZoom函数中,可以显式地设置yLeftScaledomain:

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中,设置zoomLeftscaletranslate:

myZoom = ->
  zoomLeft.scale(zoom.scale()).translate(zoom.translate())
  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