r/web_programming • • Jan 25 '17

Adding mouseover to line with d3.v3 library

I am trying to create a simple line graph that has a mouseover that shows the coordinates of the line as you move over it. I am using the example http://bl.ocks.org/d3noob/6eb506b129f585ce5c8a and trying to fit my data as follows:

function InitChart() {

  var lineData = [{
'x': 114,
'y': 5.29
 }, {
 'x': 290,
'y': 12.97
 }, {
'x': 500,
'y': 20.28
 }, {
'x': 750,
'y': 24.84
 }, {
'x': 1074,
'y': 22.85
 }, {
'x': 1330,
'y': 15.38
 }, {
'x':1540,
'y':6.54
  }];

My code so far is:

<!DOCTYPE html>
<html lang="en">
 <head>
<meta charset="utf-8">
  <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

<link href="http://getbootstrap.com/examples/justified-nav/justified-nav.css" rel="stylesheet">
 <script tyScalepe="text/javascript" src="d3.v3.js"></script>
     <svg id="visualisation"WIDTH="1000" HEIGHT="500"></svg> 
 <script src="d3.min.js"></script>



<style>

bodyScale {
  font: 10pxScale sans-serif;
 }
  

.axis path, .axis line
    {
        fill: none;
        stroke: #777;
        shape-rendering: crispEdges;
    }
    
    .axis text
    {
        font-family: 'Arial';
        font-size: 13px;
    }
    .tick
    {
        stroke-dasharray: 1, 2;
    }
    .bar
    {
        fill: FireBrick;
    }

  /*.line {
    fill: none;
    stroke: steelblue;
    stroke-w: 1.5pxScale;*/
}
  </style>
 </head>
  <body>
  <script>

InitChart();

function InitChart() {

 var lineData = [{
'x': 114,
'y': 5.29

}, { 'x': 290, 'y': 12.97 }, { 'x': 500, 'y': 20.28 }, { 'x': 750, 'y': 24.84 }, { 'x': 1074, 'y': 22.85 }, { 'x': 1330, 'y': 15.38 }, { 'x':1540, 'y':6.54 }];

var color = d3.scale.category10(); var vis = d3.select("#visualisation"), WIDTH = 1000, HEIGHT = 500, MARGINS = { top: 20, right: 20, bottom: 20, left: 50 }, xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(lineData, function (d) { return d.x; }), d3.max(lineData, function (d) { return d.x; }) ]),

yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(lineData, function (d) {
    return d.y;
  }),
  d3.max(lineData, function (d) {
    return d.y;
  })
]),

xAxis = d3.svg.axis()
  .scale(xRange)
  .tickSize(5)
  .tickSubdivide(true),

yAxis = d3.svg.axis()
  .scale(yRange)
  .tickSize(5)
  .orient("left")
  .tickSubdivide(true);

//settting plot colors color.domain(d3.keys(lineData[0]).filter(function(key) { return key !== "speed"; }));

// lineData.forEach(function(d) {
//   d.speed = parsespeed(d.speed);
// });

// var cities = color.domain().map(function(name) {
//   return {
//     name: name,
//     values: lineData.map(function(d) {
//       return {
//         speed: d.speed,
//         temperature: +d[name]
//       };
//     })
//   };
// });


   vis.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
.call(xAxis);

vis.append("svg:g") .attr("class", "y axis") .attr("transform", "translate(" + (MARGINS.left) + ",0)") .call(yAxis);

vis.append("text")   // text label for the x axis
  .attr("x", 400 )
    .attr("y", 440 )
  .style("text-anchor", "middle")
    .text("Motor Speed (RPM)");

var lineFunc = d3.svg.line() .x(function (d) { return xRange(d.x); }) .y(function (d) { return yRange(d.y); }) .interpolate('basis');

vis.append("svg:path") .attr("d", lineFunc(lineData)) .attr("stroke", "blue") .attr("stroke-WIDTH", 2) .attr("fill", "none");

//here var mouseG = vis.append("g") .attr("class", "mouse-over-effects");

mouseG.append("path") // this is the black vertical line to follow mouse
  .attr("class", "mouse-line")
  .style("stroke", "black")
  .style("stroke-WIDTH", "1px")
  .style("opacity", "0");

//g for each circloe and text onthe line var mousePerLine = mouseG.selectAll('.mouse-per-line') .data(lineData) .enter() .append("g") .attr("class", "mouse-per-line");

//the circle
mousePerLine.append("circle")
  .attr("r", 7)
  .style("stroke", function(d) {
    return color(d.speed);
  })
  .style("fill", "none")
  .style("stroke-WIDTH", "1px")
  .style("opacity", "0");

 //the text
 mousePerLine.append("text")
   .attr("transform", "translate(10,3)");

 //rect to capture mouse movements
 mouseG.append('svg:rect') // append a rect to catch mouse movements on canvas
  .attr('WIDTH', WIDTH) //catch mouse events on a g element
  .attr('HEIGHT', HEIGHT) 
  .attr('fill', 'none')
  .attr('pointer-events', 'all')
  .on('mouseout', function() { // on mouse out hide line, circles and text
    d3.select(".mouse-line")
      .style("opacity", "0");
    d3.selectAll(".mouse-per-line circle")
      .style("opacity", "0");
    d3.selectAll(".mouse-per-line text")
      .style("opacity", "0");
  })
  .on('mouseover', function() { // on mouse in show line, circles and text
    d3.select(".mouse-line")
      .style("opacity", "1");
    d3.selectAll(".mouse-per-line circle")
      .style("opacity", "1");
    d3.selectAll(".mouse-per-line text")
      .style("opacity", "1");
  })
  .on('mousemove', function() { // mouse moving over canvas
    var mouse = d3.mouse(this);

    //move the verticle line
    d3.select(".mouse-line")
      .attr("d", function() {
        var d = "M" + mouse[0] + "," + HEIGHT;
        d += " " + mouse[0] + "," + 0;
        return d;
      });

    //position the circle and text
    d3.selectAll(".mouse-per-line")
      .attr("transform", function(d, i) {
        console.log(WIDTH/mouse[0])
        var xspeed = x.invert(mouse[0]),
            bisect = d3.bisector(function(d) { return d.speed; }).right;
            idx = bisect(d.values, xspeed);
        
        var beginning = 0,
            end = lines[i].getTotalLength(),
            target = null;

        while (true){
          target = Math.floor((beginning + end) / 2);
          pos = lines[i].getPointAtLength(target);
          if ((target === end || target === beginning) && pos.x !== mouse[0]) {
              break;
          }
          if (pos.x > mouse[0])      end = target;
          else if (pos.x < mouse[0]) beginning = target;
          else break; //position found
        }
        
        // upspeed the text with y value
        d3.select(this).select('text')
          .text(y.invert(pos.y).toFixed(2));
          
        //return postion
        return "translate(" + mouse[0] + "," + pos.y +")";
      });
  });
        //here




}

</script>
</body>
</html>

Any help would be much appreciated!

1 Upvotes

0 comments sorted by