I'm new to D3 and trying to figure out how to add a circle to the chart with a tooltip attached. I want to be able to apply notes to the chart at different dates and prices. The note text should popup in the tooltip.
Here is an example I'm working on. I want a circle to appear on x = March 1 at ay price = 1000.
I added a div.tooltip in the css like this:
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;
}
In the main function that draws the chart I added a call to showNotes(), like this:
showNotes(x,y)
where x and y are defined:
var x = d3.scale.ordinal()
.rangeBands([0, width]);
var y = d3.scale.linear()
.rangeRound([height, 0]);
I created one note in an array like this:
var timeStamp = new Date("March 1, 2016");
var notes = [{"TIMESTAMP":timeStamp,"PRICE":1000.0,"NOTE":"Hello World!"}];
Then the function showNotes(x,y) is:
function showNotes(x,y) {
// Define the div for the tooltip
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
d3.select("#chart1").selectAll("note")
.data(notes)
.enter().append("circle")
.attr("r", 50)
.attr("cx", function(d) { return x(d.TIMESTAMP); })
.attr("cy", function(d) { return y(d.PRICE); })
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div .html(d.NOTE)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
});
}
A circle is supposed to appear on the chart at x=March 1, 2016, y=1000.0. And when I hover over it, the note "Hello World" is supposed to show. But the circle doesn't even show up. There are no errors in the chrome console. What am I doing wrong?
The selector d3.select("#chart1")
is incorrect as it returns a position above the SVG element. You want to select the elements under the SVG element (the g
elements) so that the note
elements you insert become children of the SVG
element.
Changing the selector to d3.select("#chart1 svg g")
solves the problem and shows the circle and tooltip correctly.
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.