Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 limit zoom level for time axis

My code is below for zooming on time X-axis. I want to set a limit in between time should zoom in or out i.e. upper limit and lower limit of time. I've tried to put boundaries value in zoomed function which was suggested in this d3 graph with limited zoom thread. but it isn't working.

var x = d3.time
  .scale()
  .domain([start_date, end_date])
  .range([0, width]);

var zoom = d3.behavior
  .zoom()
  .x(x)
  .on("zoom", zoomed);

svg = d3
  .select("#chart" + k)
  .append("svg:svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("svg:g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
  .call(zoom);

function zoomed() {
  svg.selectAll(".line").remove();

  makeBackground();

  svg.select(".x.axis").call(xAxis);
  d3.select(".x.axis.top").call(xAxisTop);

  svg.select(".x.grid").call(
    make_x_axis()
      .tickSize(-height, 0, 0)
      .tickFormat("")
  );
  svg.selectAll(".circle-path").remove();
  d3.selectAll(".trainTag").remove();
  drawPaths();
  drawCircle(x, y, chartBody, trainData[0]);
}
anyone have any other solution in order to set the zoom level may be for next and previous 2 hours. Thanks
like image 529
Govind Mantri Avatar asked Oct 30 '22 20:10

Govind Mantri


1 Answers

In d3 v4 the d3.zoom().scaleExtent allows to limit the user in zooming beyond the given boundaries (programmatically it may be set beyond though). These are given as factors, not as time-range. But you can surely calculate the factors yourself, using the known start- and end-time of the scale:

const minTimeMilli = 20000; // do not allow zooming beyond displaying 20 seconds
const maxTimeMilli = 6.3072e+11; // approx 20 years

const widthMilli = endTime - startTime;

const minScaleFactor = widthMilli / maxTimeMilli;
const maxScaleFactor = widthMilli / minTimeMilli;

const zoom = d3.zoom()
  .scaleExtent([minScaleFactor, maxScaleFactor])
like image 135
spawn Avatar answered Nov 12 '22 11:11

spawn