всплывающая подсказка для многострочного графика d3 v4 - PullRequest
0 голосов
/ 23 ноября 2018

Сначала я создал многострочный график с кистью и масштабированием, а сейчас пытаюсь добавить подсказку для него.Так что, когда я наведу курсор на многострочный график, я получу переменную: значение этой конкретной строкиТак как я только начал, я сослался на несколько сайтов, но нашел этот и изменил свой код.Но я просто получаю точки на разных позициях, и ничто не помогает.Если есть какая-либо ссылка, на которую я могу сослаться и изменять свой код, или любые исправления к моему коду очень помогли бы.

morley.csv

Expt	date	Speed	extra
1	2016-01-07	850	200
1	2016-01-08	740	300
1	2016-01-09	900	568
1	2016-01-10	1070	100
1	2016-01-01	930	789
1	2016-01-02	850	312
1	2016-01-03	950	864
1	2016-01-04	980	159
1	2016-01-05	980	345
1	2016-01-06	880	690




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

 .line {
        fill: none;
        stroke: steelblue;
        stroke-width: 1.5px;
    }
.zoom {
  cursor: move;
  fill: none;
  pointer-events: all;
}

div.tooltip {
  position: absolute;
  text-align: center;
  width: 60px;
  height: 28px;
  padding: 2px;
  font: 12px sans-serif;
  background: lightsteelblue;
  border: 0px;
  border-radius: 8px;
  pointer-events: none;
}

</style>
<svg width="960" 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("%Y-%m-%d");

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

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

//slider that grey selection one
var brush = d3.brushX()
    .extent([[0, 0], [width, height2]])
    .on("brush end", brushed);

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

    var line = d3.line()
        .x(function (d) { return x(d.date); })
        .y(function (d) { return y(d.extra); });
    
    var line1 = d3.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.Speed); });

//slider line
    var line2 = d3.line()
        .x(function (d) { return x2(d.date); })
        .y(function (d) { return y2(d.Speed); });

    var clip = svg.append("defs").append("svg:clipPath")
        .attr("id", "clip")
        .append("svg:rect")
        .attr("width", width)
        .attr("height", height)
        .attr("x", 0)
        .attr("y", 0); 

    var Line_chart = svg.append("g")
        .attr("class", "focus")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
        .attr("clip-path", "url(#clip)");

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

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



//tooltip
var div = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);




d3.csv("data/morley.csv", type, function (error, data) {
  if (error) throw error;

   data.sort(function(a,b){
       return a.date-b.date
   });
  
  x.domain(d3.extent(data, function(d) { return d.date; }));
  y.domain([0, d3.max(data, function(d) {
      return Math.max(d.Speed, d.extra); })]);
      //slider
   x2.domain(x.domain());
   y2.domain(y.domain());

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

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

    Line_chart.append("path")
        .datum(data)
        .attr("class", "line line-extra")
        .style("stroke", "green")
        .attr("d", line);

    Line_chart.append("path")
        .datum(data)
        .attr("class", "line line-speed")
        .style("stroke", "blue")
        .attr("d", line1);

//slider line
    context.append("path")
        .datum(data)
        .attr("class", "line")
        .attr("d", line2);

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

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

  svg.append("rect")
      .attr("class", "zoom")
      .attr("width", width)
      .attr("height", height)
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
      .call(zoom);
 // console.log(data);

 //tooltip
 svg.selectAll("dot")
     .data(data)
   .enter().append("circle")
     .attr("r", 5)
     .attr("cx", function(d) { return x(d.date); })
     .attr("cy", function(d) { return y(d.Speed); })
     .on("mouseover", function(d) {
       div.transition()
         .duration(200)
         .style("opacity", .9);
       div.html(formatTime(d.date) + "<br/>" + d.Speed)
         .style("left", (d3.event.pageX) + "px")
         .style("top", (d3.event.pageY - 28) + "px");
       })
     .on("mouseout", function(d) {
       div.transition()
         .duration(500)
         .style("opacity", 0);
       });

svg.selectAll("dot")
     .data(data)
   .enter().append("circle")
     .attr("r", 5)
     .attr("cx", function(d) { return x(d.date); })
     .attr("cy", function(d) { return y(d.extra); })
     .on("mouseover", function(d) {
       div.transition()
         .duration(200)
         .style("opacity", .9);
       div.html(formatTime(d.date) + "<br/>" + d.extra)
         .style("left", (d3.event.pageX) + "px")
         .style("top", (d3.event.pageY - 28) + "px");
       })
     .on("mouseout", function(d) {
       div.transition()
         .duration(500)
         .style("opacity", 0);
       });



});


function updateLines() {
  Line_chart.select(".line-extra").attr("d", line);
  Line_chart.select(".line-speed").attr("d", line1);
}
//selection in slider
function brushed() {
  if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; 
  var s = d3.event.selection || x2.range();
  x.domain(s.map(x2.invert, x2));
  Line_chart.select(".line").attr("d", line);
  focus.select(".axis--x").call(xAxis);
  svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
      .scale(width / (s[1] - s[0]))
      .translate(-s[0], 0));
      updateLines();
}

function zoomed() {
  if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return;
  var t = d3.event.transform;
  x.domain(t.rescaleX(x2).domain());
  Line_chart.select(".line").attr("d", line);
  focus.select(".axis--x").call(xAxis);
  context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
  updateLines();

}


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

</script>
...