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 tried using:
vis.selectAll("circle")
.data(datafiltered).enter().append("svg:circle")
.attr("cx", function(d) { return x(d.x);})
.attr("cy", function(d) {return y(d.y)})
.attr("fill", "red").attr("r", 15)
.on("mouseover", function() {
d3.select(this).enter().append("text")
.text(function(d) {return d.x;})
.attr("x", function(d) {return x(d.x);})
.attr("y", function (d) {return y(d.y);}); });
I suspect I need to be more informative about what data to enter?
I assume that what you want is a tooltip. The easiest way to do this is to append an
svg:title
element to each circle, as the browser will take care of showing the tooltip and you don't need the mousehandler. The code would be something likeIf you want fancier tooltips, you could use tipsy for example. See here for an example.
There is an awesome library for doing that that I recently discovered. It's simple to use and the result is quite neat: d3-tip.
You can see an example here:
Basically, all you have to do is to download(index.js), include the script:
and then follow the instructions from here (same link as example)
But for your code, it would be something like:
define the method:
create your svg (as you already do)
call the method:
add tip to your object:
Don't forget to add the CSS:
A really good way to make a tooltip is described here: Simple D3 tooltip example
You have to append a div
Then you can just toggle it using
d3.event.pageX
/d3.event.pageY
is the current mouse coordinate.If you want to change the text you can use
tooltip.text("my tooltip text");
Working Example
This concise example demonstrates common way how to create custom tooltip in d3.
You can pass in the data to be used in the mouseover like this- the mouseover event uses a function with your previously
enter
ed data as an argument (and the index as a second argument) so you don't need to useenter()
a second time.