简体   繁体   中英

display tooltip on a node in d3.js

I am trying to display tooltip to the displayed nodes in the graph using D3.js and how would I display tooltip based on calculation like if scatterplot lies between 2013 and 2014 I want to calculate specific column in csv and disply tooltip for those nodes? How can I do so?

Following is the code I using to display tooltip:

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

Following is the link for my script on Plunker: Display tooltip in Scatterplot

My solution comes in two parts: first, computing the totals by year and then referencing those in the function that creates the tooltip. For the first part, I'm using the d3.nest() operator :

var byYear = d3.nest()
  .key(function(d) { return d.created_at.getFullYear(); })
  .rollup(function(d) {
    return d.reduce(function(prev, cur) {
      prev.retweet_count += cur.retweet_count;
      prev.favorite_count += cur.favorite_count;
      return prev;
    }, {retweet_count: 0, favorite_count: 0});
})
.map(data);

This computes the sums of retweet_count and favorite_count by year, creating an associative array that you can index into using the year. This is then used to create the tooltip:

.append("title")
    .text(function(d) {
      var year = d.created_at.getFullYear();
      var totals = byYear[year];
      return d["favorite_count"] + " (" + xValue(d) + ", " + yValue(d) + ")" +
        " retweets: " + totals.retweet_count + ", favorites: " + totals.favorite_count;
  });

(I've changed it to be a title element as the definition of tooltip was missing from your example.) This gets the year of the current element, indexes into the array we've created earlier and retrieves the totals from it. The rest is just putting the string together.

Complete demo here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM