JavaScript D3 : zoom

标签 javascript d3.js visualization data-visualization

我有这个 HTML 页面,但我刚刚实现了一项新功能:当我将鼠标悬停在图表上时,创建一条垂直线来打印 y 轴的当前值。但是,添加此功能后,我无法再使用鼠标滚轮缩放图表。我怎样才能做到这一点?谢谢。

这是 HTML 页面:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
  .area {
    fill: #ffe368;
    opacity: 0.6;
    clip-path: url(#clip);
  }

  .areax {
    fill: #8cffa4;
    opacity: 0.6;
    clip-path: url(#clip);
  }

  .zoom {
    cursor: move;
    fill: none;
    pointer-events: all;
  }

  body {
    background-color: #F1F3F3
  }

  .axis {
    font: 10px sans-serif;
  }

  .axis path,
  .axis line {
    fill: none;
    stroke: #D4D8DA;
    stroke-width: 2px;
    shape-rendering: crispEdges;
  }

  .line {
    fill: none;
    stroke: #6F257F;
    stroke-width: 5px;
  }

  .overlay {
    fill: none;
    pointer-events: all;
  }

  .focus circle {
    fill: #F1F3F3;
    stroke: #6F257F;
    stroke-width: 5px;
  }

  .hover-line {
    stroke: #6F257F;
    stroke-width: 2px;
    stroke-dasharray: 3, 3;
  }
</style>
<svg width="1200" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
  var svg = d3.select("svg"),
    margin = {
      top: 20,
      right: 20,
      bottom: 110,
      left: 40
    },
    margin2 = {
      top: 430,
      right: 20,
      bottom: 30,
      left: 40
    },
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    height2 = +svg.attr("height") - margin2.top - margin2.bottom;

  var parseDate = d3.timeParse("%b %Y")
  bisectDate = d3.bisector(function(d) {
    return d.date;
  }).left;;

  var x = d3.scaleTime().range([0, width]),
    x2 = d3.scaleTime().range([0, width]),
    y = d3.scaleLinear().range([height, 0]),
    y2 = d3.scaleLinear().range([height2, 0]);

  var xAxis = d3.axisBottom(x),
    xAxis2 = d3.axisBottom(x2),
    yAxis = d3.axisLeft(y);

  var brush = d3.brushX()
    .extent([
      [0, 0],
      [width, height2]
    ])
    .on("brush end", brushed);

  var zoom = d3.zoom()
    .scaleExtent([1, 10])
    .translateExtent([
      [0, 0],
      [width, height]
    ])
    .extent([
      [0, 0],
      [width, height]
    ])
    .on("zoom", zoomed);

  var area = d3.area()
    .curve(d3.curveMonotoneX)
    .x(function(d) {
      return x(d.date);
    })
    .y0(height)
    .y1(function(d) {
      return y(d.price);
    });

  var area2 = d3.area()
    .curve(d3.curveMonotoneX)
    .x(function(d) {
      return x2(d.date);
    })
    .y0(height2)
    .y1(function(d) {
      return y2(d.price);
    });

  svg.append("defs").append("clipPath")
    .attr("id", "clip")
    .append("rect")
    .attr("width", width)
    .attr("height", height);

  var g = svg.append("g") // riferito al primo piano
    // .attr("class", "focus")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var context = svg.append("g") // riferito al secondo piano
    .attr("class", "context")
    .attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");

  var data = [
    {date: 'Jan 2000', price: 9}, 
    {date: 'Feb 2000', price: 20}, 
    {date: 'Mar 2000', price: 2}, 
    {date: 'Apr 2000', price: 9}, 
    {date: 'May 2000', price: 11}, 
    {date: 'Jun 2000', price: 12}, 
    {date: 'Jul 2000', price: 21}, 
    {date: 'Aug 2000', price: 9}, 
    {date: 'Sep 2000', price: 15}, 
    {date: 'Oct 2000', price: 6}, 
    {date: 'Nov 2000', price: 49}, 
    {date: 'Dec 2000', price: 48}, 
    {date: 'Jan 2001', price: 55}, 
    {date: 'Feb 2001', price: 20}, 
    {date: 'Mar 2001', price: 2}, 
    {date: 'Apr 2001', price: 11}, 
    {date: 'May 2001', price: 49}, 
    {date: 'Jun 2001', price: 9}, 
    {date: 'Jul 2001', price: 32}, 
    {date: 'Aug 2001', price: 31}, 
    {date: 'Sep 2001', price: 12}, 
    {date: 'Oct 2001', price: 34}, 
    {date: 'Nov 2001', price: 11}, 
    {date: 'Dec 2001', price: 22}
  ];

  var datax = [
    {date: 'Jan 2000', price: 55}, 
    {date: 'Feb 2000', price: 3}, 
    {date: 'Mar 2000', price: 22}, 
    {date: 'Apr 2000', price: 2}, 
    {date: 'May 2000', price: 11}, 
    {date: 'Jun 2000', price: 23}, 
    {date: 'Jul 2000', price: 21}, 
    {date: 'Aug 2000', price: 19}, 
    {date: 'Sep 2000', price: 15}, 
    {date: 'Oct 2000', price: 16}, 
    {date: 'Nov 2000', price: 9}, 
    {date: 'Dec 2000', price: 18}, 
    {date: 'Jan 2001', price: 55}, 
    {date: 'Feb 2001', price: 20}, 
    {date: 'Mar 2001', price: 2}, 
    {date: 'Apr 2001', price: 33}, 
    {date: 'May 2001', price: 31}, 
    {date: 'Jun 2001', price: 9}, 
    {date: 'Jul 2001', price: 32}, 
    {date: 'Aug 2001', price: 7}, 
    {date: 'Sep 2001', price: 12}, 
    {date: 'Oct 2001', price: 2}, 
    {date: 'Nov 2001', price: 2}, 
    {date: 'Dec 2001', price: 3}
  ];

  data.forEach(function(d) {
    d.date = parseDate(d.date);
    d.price = +d.price;
  });

  datax.forEach(function(d) {
    d.date = parseDate(d.date);
    d.price = +d.price;
  });

  x.domain(d3.extent(data, function(d) {
    return d.date;
  }));
  y.domain([d3.min(data, function(d) {
    return d.price;
  }), d3.max(data, function(d) {
    return d.price;
  })]);

  x2.domain(x.domain());
  y2.domain(y.domain());

  g.append("path")
    .datum(data)
    .attr("class", "area")
    .attr("d", area);

  g.append("path")
    .datum(datax)
    .attr("class", "areax")
    .attr("d", area);

  g.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  /*focus.append("g")
      .attr("class", "axis axis--y")
      .call(yAxis); */

  g.append("g")
    .attr("class", "axis axis--y")
    .call(d3.axisLeft(y).ticks(6).tickFormat(function(d) {
      return parseInt(d / 1000) + "k";
    }))
    .append("text")
    .attr("class", "axis-title")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")
    .attr("fill", "#5D6971")
    .text("Visitatori)");

  var focus = g.append("g")
    .attr("class", "focus")
    .style("display", "none");

  focus.append("line")
    .attr("class", "x-hover-line hover-line")
    .attr("y1", 0)
    .attr("y2", height);

  focus.append("line")
    .attr("class", "y-hover-line hover-line")
    .attr("x1", width)
    .attr("x2", width);

  focus.append("circle")
    .attr("r", 7.5);

  focus.append("text")
    .attr("x", 15)
    .attr("dy", ".31em");

  context.append("path")
    .datum(data)
    .attr("class", "area")
    .attr("d", area2);

  context.append("path")
    .datum(datax)
    .attr("class", "areax")
    .attr("d", area2);

  context.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + height2 + ")")
    .call(xAxis2);

  context.append("g")
    .attr("class", "brush")
    .call(brush)
    .call(brush.move, x.range());

  svg.append("rect")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
    .attr("class", "overlay")
    .attr("class", "zoom")
    .attr("width", width)
    .attr("height", height)
    .call(zoom)
    // .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
    .on("mouseover", function() {
      focus.style("display", null);
    })
    .on("mouseout", function() {
      focus.style("display", "none");
    })
    .on("mousemove", mousemove);

  function brushed() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
    var s = d3.event.selection || x2.range();
    x.domain(s.map(x2.invert, x2));
    focus.select(".area").attr("d", area);
    focus.select(".areax").attr("d", area);
    focus.select(".axis--x").call(xAxis);
    svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
      .scale(width / (s[1] - s[0]))
      .translate(-s[0], 0));
  }

  function zoomed() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return; // ignore zoom-by-brush
    var t = d3.event.transform;
    x.domain(t.rescaleX(x2).domain());
    focus.select(".area").attr("d", area);
    focus.select(".areax").attr("d", area);
    focus.select(".axis--x").call(xAxis);
    context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
  }

  function mousemove() {
    var x0 = x.invert(d3.mouse(this)[0]),
      i = bisectDate(data, x0, 1),
      d0 = data[i - 1],
      d1 = data[i],
      d = x0 - d0.date > d1.date - x0 ? d1 : d0;
    focus.attr("transform", "translate(" + x(d.date) + "," + y(d.price) + ")");
    focus.select("text").text(function() {
      return d.price;
    });
    focus.select(".x-hover-line").attr("y2", height - y(d.price));
    focus.select(".y-hover-line").attr("x2", width + width);
  }
</script>

最佳答案

小修复:在您的zoomed 函数中,您正在focus.area、.areax 和.axis--x > 当他们不在焦点小组时。只需将其更改为:

g.select(".area").attr("d", area);
g.select(".areax").attr("d", area);
g.select(".axis--x").call(xAxis);

这是一个片段:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.area {
  fill: #ffe368;
  opacity: 0.6;
  clip-path: url(#clip);   
}

.areax {
  fill: #8cffa4;
  opacity: 0.6;
  clip-path: url(#clip);   
}

.zoom {
  cursor: move;
  fill: none;
  pointer-events: all;
}

body {
  background-color: #F1F3F3    
}
.axis {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #D4D8DA;
  stroke-width: 2px;
  shape-rendering: crispEdges;
}

.line {
  fill: none;
  stroke: #6F257F;
  stroke-width: 5px;
}

.overlay {
  fill: none;
  pointer-events: all;
}

.focus circle {
  fill: #F1F3F3;
  stroke: #6F257F;
  stroke-width: 5px;
}

.hover-line {
  stroke: #6F257F;
  stroke-width: 2px;
  stroke-dasharray: 3,3;
}

</style>
<svg width="1200" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 110, left: 40},
    margin2 = {top: 430, right: 20, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    height2 = +svg.attr("height") - margin2.top - margin2.bottom;

var parseDate = d3.timeParse("%b %Y")
    bisectDate = d3.bisector(function(d) { return d.date; }).left;;   

var x = d3.scaleTime().range([0, width]),  
    x2 = d3.scaleTime().range([0, width]), 
    y = d3.scaleLinear().range([height, 0]),
    y2 = d3.scaleLinear().range([height2, 0]);

var xAxis = d3.axisBottom(x),
    xAxis2 = d3.axisBottom(x2),
    yAxis = d3.axisLeft(y);

var brush = d3.brushX()
    .extent([[0, 0], [width, height2]])
    .on("brush end", brushed);

var zoom = d3.zoom()
    .scaleExtent([1, 10])  
    .translateExtent([[0, 0], [width, height]])
    .extent([[0, 0], [width, height]])
    .on("zoom", zoomed);

var area = d3.area()
    .curve(d3.curveMonotoneX)
    .x(function(d) { return x(d.date); })
    .y0(height)
    .y1(function(d) { return y(d.price); });

var area2 = d3.area()
    .curve(d3.curveMonotoneX)
    .x(function(d) { return x2(d.date); })
    .y0(height2)
    .y1(function(d) { return y2(d.price); });

svg.append("defs").append("clipPath")
    .attr("id", "clip")
  .append("rect")
    .attr("width", width)
    .attr("height", height);

var g = svg.append("g")  // riferito al primo piano
   // .attr("class", "focus")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var context = svg.append("g") // riferito al secondo piano
    .attr("class", "context")
    .attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");



var data = [{date: 'Jan 2000', price: 9}, {date: 'Feb 2000', price:20},{date: 'Mar 2000', price: 2}, {date: 'Apr 2000', price: 9}, {date: 'May 2000', price: 11}, {date: 'Jun 2000', price: 12}, {date: 'Jul 2000', price: 21}, {date: 'Aug 2000', price: 9}, {date: 'Sep 2000', price: 15}, {date: 'Oct 2000', price: 6}, {date: 'Nov 2000', price: 49}, {date: 'Dec 2000', price: 48}, {date: 'Jan 2001', price: 55}, {date: 'Feb 2001', price:20},{date: 'Mar 2001', price: 2}, {date: 'Apr 2001', price: 11}, {date: 'May 2001', price: 49}, {date: 'Jun 2001', price: 9}, {date: 'Jul 2001', price: 32}, {date: 'Aug 2001', price: 31}, {date: 'Sep 2001', price: 12}, {date: 'Oct 2001', price: 34}, {date: 'Nov 2001', price: 11}, {date: 'Dec 2001', price: 22}];



var datax = [{date: 'Jan 2000', price: 55}, {date: 'Feb 2000', price:3},{date: 'Mar 2000', price: 22}, {date: 'Apr 2000', price: 2}, {date: 'May 2000', price: 11}, {date: 'Jun 2000', price: 23}, {date: 'Jul 2000', price: 21}, {date: 'Aug 2000', price: 19}, {date: 'Sep 2000', price: 15}, {date: 'Oct 2000', price: 16}, {date: 'Nov 2000', price: 9}, {date: 'Dec 2000', price: 18}, {date: 'Jan 2001', price: 55}, {date: 'Feb 2001', price:20},{date: 'Mar 2001', price: 2}, {date: 'Apr 2001', price: 33}, {date: 'May 2001', price: 31}, {date: 'Jun 2001', price: 9}, {date: 'Jul 2001', price: 32}, {date: 'Aug 2001', price: 7}, {date: 'Sep 2001', price: 12}, {date: 'Oct 2001', price: 2}, {date: 'Nov 2001', price: 2}, {date: 'Dec 2001', price: 3}];

data.forEach(function (d) {
  d.date = parseDate(d.date);
  d.price = +d.price;
});

datax.forEach(function (d) {
  d.date = parseDate(d.date);
  d.price = +d.price;
}); 



  x.domain(d3.extent(data, function(d) { return d.date; })); 
  y.domain([d3.min(data, function(d) { return d.price; }), d3.max(data, function(d) { return d.price; })]); 

  x2.domain(x.domain());
  y2.domain(y.domain());

  g.append("path")
      .datum(data)
      .attr("class", "area")
      .attr("d", area);

  g.append("path")
      .datum(datax)
      .attr("class", "areax")
      .attr("d", area);

  g.append("g")
      .attr("class", "axis axis--x")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  /*focus.append("g")
      .attr("class", "axis axis--y")
      .call(yAxis); */

  g.append("g")
        .attr("class", "axis axis--y")
        .call(d3.axisLeft(y).ticks(6).tickFormat(function(d) { return parseInt(d / 1000) + "k"; }))
      .append("text")
        .attr("class", "axis-title")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .attr("fill", "#5D6971")
        .text("Visitatori)");

 var focus = g.append("g")
        .attr("class", "focus")
        .style("display", "none"); 

  focus.append("line")
        .attr("class", "x-hover-line hover-line")
        .attr("y1", 0)
        .attr("y2", height);

  focus.append("line")
        .attr("class", "y-hover-line hover-line")
        .attr("x1", width)
        .attr("x2", width);

  focus.append("circle")
        .attr("r", 7.5);

  focus.append("text")
        .attr("x", 15)
        .attr("dy", ".31em");

  context.append("path")
      .datum(data)
      .attr("class", "area")
      .attr("d", area2);

  context.append("path")
      .datum(datax)
      .attr("class", "areax")
      .attr("d", area2);

  context.append("g")
      .attr("class", "axis axis--x")
      .attr("transform", "translate(0," + height2 + ")")
      .call(xAxis2);

  context.append("g")
      .attr("class", "brush")
      .call(brush)
      .call(brush.move, x.range());

  svg.append("rect")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
      .attr("class", "overlay")
      .attr("class", "zoom")
      .attr("width", width)  
      .attr("height", height)
      .call(zoom)
     // .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
      .on("mouseover", function() { focus.style("display", null); })
      .on("mouseout", function() { focus.style("display", "none"); })
      .on("mousemove", mousemove);




function brushed() {
  if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
  var s = d3.event.selection || x2.range();
  x.domain(s.map(x2.invert, x2));
  focus.select(".area").attr("d", area);
  focus.select(".areax").attr("d", area);
  focus.select(".axis--x").call(xAxis);
  svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
      .scale(width / (s[1] - s[0]))
      .translate(-s[0], 0));
}

function zoomed() {
  if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return; // ignore zoom-by-brush
  var t = d3.event.transform;
  x.domain(t.rescaleX(x2).domain());
  g.select(".area").attr("d", area);
  g.select(".areax").attr("d", area);
  g.select(".axis--x").call(xAxis);
  context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
}

function mousemove() {
      var x0 = x.invert(d3.mouse(this)[0]),
          i = bisectDate(data, x0, 1),
          d0 = data[i - 1],
          d1 = data[i],
          d = x0 - d0.date > d1.date - x0 ? d1 : d0;
      focus.attr("transform", "translate(" + x(d.date) + "," + y(d.price) + ")");
      focus.select("text").text(function() { return d.price; });
      focus.select(".x-hover-line").attr("y2", height - y(d.price));
      focus.select(".y-hover-line").attr("x2", width + width);
    }



</script>

关于JavaScript D3 : zoom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51485633/

相关文章:

javascript - 当链接太多时,d3 sankey 插件无法绘制?

python - 双变量 CDF/CCDF 分布 Python

javascript - 移动到 SVG 路径 (d3.js) 中的鼠标单击

javascript - 通过更改输入选择的数据,使用 d3 v3.js 在堆叠条形图中进行过滤

javascript - 如果Child组件动态组件,如何将数据从Child传递到Parent

javascript - 在 PhoneGap - Jquerymobile 应用程序上多次触发事件(甚至循环)

r - 在 R 中可视化纵向分类数据的好方法

javascript - D3 X轴长标签重叠

javascript - 使用knockout js构建的无限滚动在IE9中不起作用

javascript - 从非公共(public)文件夹获取 zip 文件 (php)