简体   繁体   中英

How to re-position datapoints in d3?

I want to implement an x axis "zoom" by having a slidebar that allows the user to "zoom" into the x axis. Rescaling the x axis works, but my data points stay at the same location, ie. they don't rescale. How can I simultaneously scale axis and data point locations?

The 'container' element contains all the datapoints. This is what I call to draw the points:

xValue = function(d) {return d[2]};
xScale = d3.scale.linear().range([0, width]);
xMap = function(d) {return xScale(xValue(d))};
xAxis = d3.svg.axis().ticks(5).scale(xScale).orient("top");

container.selectAll(".dot")
      .data(datajson)
      .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 3.5)
      .attr("cx", xMap)
      .attr("cy", yMap)
      .style("fill", function(d) { return color(cValue(d));}); 

And here is my code to rescale the x axis, executed through a slider:

d3.select("#graphzoom").on("input", function() {
  curMin = getNewMinimum();
  curMax = getNewMaximum();
  xScale.domain([curMin,curMax]);
  container.selectAll("g.x.axis").call(xAxis);
});

How can I also rescale the point positions?

Redrawing your graph when you xAxis is changed will solve your problem.

Also you can try transition() for nice effect.

d3.select("#graphzoom").on("input", function() {
  curMin = getNewMinimum();
  curMax = getNewMaximum();
  xScale.domain([curMin,curMax]);
  container.selectAll("g.x.axis").call(xAxis);

  container.selectAll(".dot").remove();
  container.selectAll(".dot").
      .data(datajson)
      .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 3.5)
      .attr("cx", xMap)
      .attr("cy", yMap)
      .style("fill", function(d) { return color(cValue(d));}); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM