javascript – 具有x / y轴和鼠标悬停示例的倍数 – 线路径显示错误的值

我试图结合基于
example的严格D3.js示例.我设法在部分工作中为每个多重图表获取鼠标悬停(值不会显示在鼠标指针但是通过console.log).通过检查这些值,我意识到上面两个图表中的线路路径相对于Y轴是关闭的,也导致鼠标悬停焦点位于错误的位置.我是D3的新手,所以我仍然无法确定由域/比例/轴等引起的问题.您可以看到示例
here

这是我的代码:

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

body {
  font: 10px sans-serif;
  margin: 0;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  //shape-rendering: crispEdges;
}

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.area {
  //fill: #e7e7e7;
  fill: transparent;
}

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

.focus circle {
  fill: none;
  stroke: steelblue;
}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>

var margin = {top: 8, right: 10, bottom: 20, left: 30},
    width = 960 - margin.left - margin.right,
    height = 138 - margin.top - margin.bottom;

var parseDate = d3.time.format("%b %Y").parse,
    bisectDate = d3.bisector(function(d) { return d.date; }).left,
    formatValue = d3.format(",.2f"),
    formatCurrency = function(d) { return formatValue(d); };

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

var y = d3.scale.linear()
    .range([height, 0]);

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

var line = d3.svg.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.price); });

var xAxis = d3.svg.axis()
  .scale(x)         // x is the d3.time.scale()
  .orient("bottom") // the ticks go below the graph
  .ticks(4);        // specify the number of ticks

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(4);

d3.csv("stocks_chart2.csv", type, function(error, data) {

    // Nest data by symbol.
    var symbols = d3.nest()
      .key(function(d) { return d.symbol; })
      .entries(data);

    // Compute the maximum price per symbol, needed for the y-domain.
    symbols.forEach(function(s) {
    s.maxPrice = d3.max(s.values, function(d) { return d.price; });
    });

    // Compute the minimum and maximum date across symbols.
    // We assume values are sorted by date.
    x.domain([
    d3.min(symbols, function(s) { return s.values[0].date; }),
    d3.max(symbols, function(s) { return s.values[s.values.length - 1].date; })
    ]);

    // Add an SVG element for each symbol, with the desired dimensions and margin.
    var svg = d3.select("body").selectAll("svg")
      .data(symbols)
    .enter().append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
    .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    // Add the area path elements. Note: the y-domain is set per element.
    svg.append("path")
      .attr("class", "area")
      .attr("d", function(d) { y.domain([0, d.maxPrice]); return area(d.values); });

    // Add the line path elements. Note: the y-domain is set per element.
    svg.append("path")
      .attr("class", "line")
      .attr("d", function(d) { y.domain([0, d.maxPrice]); return line(d.values); });

    // Add a small label for the symbol name.
    svg.append("text")
      .attr("x", width - 6)
      .attr("y", height - 6)
      .style("text-anchor", "end")
      .text(function(d) { return d.key; });

    svg.append('g')            // create a <g> element
      .attr('class', 'x axis') // specify classes
      .attr("transform", "translate(0," + height + ")") 
      .call(xAxis);            // let the axis do its thing

    svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Value");

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

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

    focus.append("text")
      .attr("x", 9)
      .attr("dy", ".35em");

    svg.append("rect")
      .attr("class", "overlay")
      .attr("width", width)
      .attr("height", height)
      .on("mouseover", function() { focus.style("display", null); })
      .on("mouseout", function() { focus.style("display", "none"); })
      .on("mousemove", mousemove);

  function mousemove() {
        var date, index;
        date = x.invert(d3.mouse(this)[0]);
        index = 0;
        var focus = svg.selectAll(".focus");
        focus.attr("transform", function(d) {
            index = bisectDate(d.values, date, 0, d.values.length - 1);
            console.log(index, d.values[index].symbol, d.values[index].date, d.values[index].price); 
            return "translate(" + x(d.values[index].date) + "," + y(d.values[index].price) + ")"
        });

        focus.selectAll("text", function(d) {
          return formatCurrency(d.values[index].price);
        });
    }
});

function type(d) {
  d.price = +d.price;
  d.date = parseDate(d.date);
  return d;
}

</script>

如何为每个单独的多重图表分配正确的Y轴,从而使线路径和鼠标悬停值处于正确的位置?任何帮助将不胜感激!谢谢!

最佳答案 这是一个有趣的问题.您链接到的示例使用单个y比例,yAxis用于所有4个子图.但是,在您的情况下,您的数据对于每个子图具有非常不同的域,并且当您在共享比例上添加动态鼠标时,将无法工作.因此,我的解决方案是为每个子图创建不同的y比例和yAxis.

...

// variable to hold our scales
var ys = {};

var area = d3.svg.area()
  .x(function(d) {
    return x(d.date);
  })
  .y0(height)
  .y1(function(d) {
    return ys[d.symbol](d.price); //<-- call the y function matched to our symbol
  });

var line = d3.svg.line()
  .x(function(d) {
    return x(d.date);
  })
  .y(function(d, i) {
    return ys[d.symbol](d.price); //<-- call the y scale function matched to our symbol
  });

...

// for each symbol create our scale
symbols.forEach(function(s) {
  var maxPrice = d3.max(s.values, function(d) {
    return d.price;
  });
  ys[s.key] = d3.scale.linear() //<-- create a scale for each "symbol" (ie Sensor 1, etc...)
    .range([height, 0])
    .domain([0, maxPrice]);
});

...

// build 4 y axis
var axisGs = svg.append("g"); //<-- create a collection of axisGs

axisGs
  .attr("class", "y axis")
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
    .style("text-anchor", "end")
    .text("Value");

axisGs.each(function(d, i) { //<-- for each axisG create an axis with it's scale
  var self = d3.select(this);
  self.call(
    d3.svg.axis()
      .scale(ys[d.key])
      .orient("left")
      .ticks(4)
  );
});

...

// adjust mouseover to use appropriate scale
focus.attr("transform", function(d) {
  index = bisectDate(d.values, date, 0, d.values.length - 1);
  console.log(index, d.values[index].symbol, d.values[index].date, d.values[index].price);
  return "translate(" + x(d.values[index].date) + "," + ys[d.key](d.values[index].price) + ")"; //<-- finally in our mouse move use the appropriate scale
});

完全正常工作的代码here.

点赞