Show data on mouseover of circle

前端 未结 5 1333
我寻月下人不归
我寻月下人不归 2020-11-22 10:05

I have a set of data that I am plotting in a scatter. When I mouseover one of the circles I would like it to popup with data (like x, y values, maybe more). Here is what I

5条回答
  •  天命终不由人
    2020-11-22 10:33

    This concise example demonstrates common way how to create custom tooltip in d3.

    var w = 500;
    var h = 150;
    
    var dataset = [5, 10, 15, 20, 25];
    
    // firstly we create div element that we can use as
    // tooltip container, it have absolute position and
    // visibility: hidden by default
    
    var tooltip = d3.select("body")
      .append("div")
      .attr('class', 'tooltip');
    
    var svg = d3.select("body")
      .append("svg")
      .attr("width", w)
      .attr("height", h);
    
    // here we add some circles on the page
    
    var circles = svg.selectAll("circle")
      .data(dataset)
      .enter()
      .append("circle");
    
    circles.attr("cx", function(d, i) {
        return (i * 50) + 25;
      })
      .attr("cy", h / 2)
      .attr("r", function(d) {
        return d;
      })
      
      // we define "mouseover" handler, here we change tooltip
      // visibility to "visible" and add appropriate test
      
      .on("mouseover", function(d) {
        return tooltip.style("visibility", "visible").text('radius = ' + d);
      })
      
      // we move tooltip during of "mousemove"
      
      .on("mousemove", function() {
        return tooltip.style("top", (event.pageY - 30) + "px")
          .style("left", event.pageX + "px");
      })
      
      // we hide our tooltip on "mouseout"
      
      .on("mouseout", function() {
        return tooltip.style("visibility", "hidden");
      });
    .tooltip {
        position: absolute;
        z-index: 10;
        visibility: hidden;
        background-color: lightblue;
        text-align: center;
        padding: 4px;
        border-radius: 4px;
        font-weight: bold;
        color: orange;
    }

提交回复
热议问题