I am trying to create a scatter plot and want to show tooltips by clicking on each point. The tooltip will disappear only when the point is deselected (clicked again). Currently, selected points will have a black border with r=8. Deselected points have no visible black border with r=4.5.
With the code below, when I deselect the points, the tooltip won't go away. How can I link the tooltip to each point? Thanks!
.on("click", function (d) {
var clickTooltip = d3.select("#data_visualization").append("div").attr("class", "click_tooltip");
if (d3.select(this).attr("r") < 8) {
d3.select(this)
.style("stroke", "black")
.style("stroke-width", "2px")
.style("stroke-opacity", 1)
.attr("r", 8);
clickTooltip.style("opacity", 0.62);
var clickTooltipText = "display";
clickTooltip.html(clickTooltipText)
.style("left", (d3.event.pageX + 20) + "px")
.style("top", (d3.event.pageY - 40) + "px");
} else {
d3.select(this)
.attr("r", 4.5)
.style("stroke-opacity", 0);
clickTooltip.style("opacity", 0);
}
}
You are appending a new element every time the click handler is called. Instead, create the element once and then select it:
var clickTooltip = d3.select("#data_visualization").append("div").attr("class", "click_tooltip");
.on("click", function (d) {
if (d3.select(this).attr("r") < 8) {
// etc
I figured it out. I am posting my answer here in case anyone is interested. The idea is to add an ID to each tooltip div. Later we can use JQuery to remove by ID.
.on("click", function (d) {
var pointID = "point_" + d3.select(this).attr("cx").replace(".", "_") + "_" + d3.select(this).attr("cy").replace(".", "_");
var clickTooltip = d3.select("#data_visualization")
.append("div")
.attr("id", pointID)
.attr("class", "click_tooltip");
if (d3.select(this).attr("r") < 8) {
d3.select(this)
.style("stroke", "black")
.style("stroke-width", "2px")
.style("stroke-opacity", 1)
.attr("r", 8);
clickTooltip.style("opacity", 0.62);
var clickTooltipText = "display";
clickTooltip.html(clickTooltipText)
.style("left", (d3.event.pageX + 20) + "px")
.style("top", (d3.event.pageY - 40) + "px");
} else {
d3.select(this)
.attr("r", 4.5)
.style("stroke-opacity", 0);
d3.select("#" + pointID).remove();
}
}
Related
I'm newbie with D3.js and I'm trying to put a text inside a circle but I am only able to do it with one of them and not with all the circles.
You can find all the code in this snipet
And the function where I create the circles and I try to put the text inside of is "setPointsToCanvas"
setPointsToCanvas(canvas, data, scales, x_label, y_label, lang) {
canvas
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("class", "dot")
.attr("r", 20) //Radius size, could map to another dimension
.attr("cx", function(d) {
return scales.xScale(parseFloat(d.value_x));
}) //x position
.attr("cy", function(d) {
return scales.yScale(parseFloat(d.value_y));
}) //y position
.style("fill", "#FFC107")
.on("mouseover", tipMouseOver)
.on("mouseout", tipMouseOut);
//Ad label for each circle
canvas
.data(data)
//.enter()
.append("text")
.attr("x", function(d) {
return scales.xScale(parseFloat(d.value_x));
})
.attr("y", function(d) {
return scales.yScale(parseFloat(d.value_y) - 0.9);
})
.text(function(d) {
return d.name.substring(0, 3);
})
.style("text-anchor", "middle")
.style("font-weight", "bold")
.style("font-size", "10pt")
.style("fill", "#344761");
let tooltip = d3
//.select("#" + this.props.idContainer)
.select("body")
.append("div")
.attr("class", "tooltip-player")
.style("opacity", 0);
/**
* We define this function inside of setPointsToCanvas to get access to canvas, data, scales and tooltip
* #param {*} d
* #param {*} iter
*/
function tipMouseOver(d, iter) {
let players = data.filter(p => {
if (p.value_x === d.value_x && p.value_y === d.value_y) {
return p;
}
});
let html = "";
for (let i = 0; i < players.length; i++) {
let text_x =
lang === "es"
? String(parseFloat(players[i].value_x).toFixed(2)).replace(
".",
","
)
: parseFloat(players[i].value_x).toFixed(2);
let text_y =
lang === "es"
? String(parseFloat(players[i].value_y).toFixed(2)).replace(
".",
","
)
: parseFloat(players[i].value_y).toFixed(2);
if (i > 0) html += "<hr>";
html +=
players[i].name +
"<br><b>" +
x_label +
": </b>" +
text_x +
"%<br/>" +
"<b>" +
y_label +
": </b>" +
text_y +
"%";
}
tooltip
.html(html)
.style("left", d3.event.pageX + 15 + "px")
.style("top", d3.event.pageY - 28 + "px")
.transition()
.duration(200) // ms
.style("opacity", 0.9); // started as 0!
// Use D3 to select element, change color and size
d3.select(this)
//.attr("r", 10)
.style("cursor", "pointer");
}
/**
* We create this function inside of setPointsToCanvas to get access to tooltip
*/
function tipMouseOut() {
tooltip
.transition()
.duration(500) // ms
.style("opacity", 0); // don't care about position!
//d3.select(this).attr("r", 5);
}
}
And here you can see how I'm only able to get one text inside of one circle and not the text inside all of them.
What am I doing wrong?
Following the advice of #Pablo EM and thanks to #Andrew Reid for your appreciated help I publish the solution to my problem.
How #Andrew Reid said if I have problems with selectAll("text") I have to change it for another text grouper. How I had it, I changed by selectAll("textCircle") and everything works fine to me.
This is the code which writes the text inside each circle. This piede of code you can find it inside of "setPointsToCanvas" method.
//Ad label for each circle
canvas
.selectAll("textCircle")
.data(data)
.enter()
.append("text")
.attr("x", function(d) {
return scales.xScale(parseFloat(d.value_x));
})
.attr("y", function(d) {
return scales.yScale(parseFloat(d.value_y) - 0.9);
})
.text(function(d) {
return d.name.substring(0, 3);
})
.style("text-anchor", "middle")
.style("font-weight", "bold")
.style("font-size", "10pt")
.style("fill", "#344761");
Now, here you've got an image of the final result:
If you access to the code through CodeSandBox posted before you can access to all the code and check how it works perfectly.
I'm using the following example as a template to create a Bubble Chart (https://bl.ocks.org/john-guerra/0d81ccfd24578d5d563c55e785b3b40a).
I'm attempting to display a tooltip every time the mouse hovers a specific circle but for some reason it doesn't seem to work. I would also like to change the text inside the circles to white but I have been unsuccessful so far.
Here is a sample of the JSON file:
{
"name": "POR",
"children": [{
"name": "Clyde Drexler",
"size": 18040,
"color": "#D00328"
},
{
"name": "Damian Lillard",
"size": 12909,
"color": "#D00328"
},
$(document).ready(function() {
let diameter = 750;
let format = d3.format(",d");
let color = d3.scaleOrdinal(d3.schemeCategory20c);
let bubble = d3.pack()
.size([diameter, diameter])
.padding(1.5);
let svgContainer = d3.select("#data-visualisation");
// Append <svg> to body
let svg = svgContainer.append('svg')
.attr('width', diameter)
.attr('height', diameter)
.attr("align", "center")
.attr('class', 'bubble');
// Read the data
d3.json("data/flare.json", function(error, data) {
// error scenario
if (error) throw error;
let root = d3.hierarchy(classes(data))
.sum(function(d) {
return d.value;
})
.sort(function(a, b) {
return b.value - a.value;
});
bubble(root);
//////////////
// tooltip
//////////////
//Create a tooltip div that is hidden by default:
let tooltip = svgContainer
.append("div")
.style("opacity", 0)
.attr("class", "tooltip")
.style("background-color", "black")
.style("border-radius", "5px")
.style("padding", "10px")
.style("color", "white");
// Create 3 functions to show / update (when mouse move but stay on same circle) / hide the tooltip
let showTooltip = function(d) {
tooltip
.transition()
.duration(200)
tooltip
.style("opacity", 1)
.html("Player: " + d.data.className + "<br> Points with franchise: " + d.data.value)
.style("left", (d3.mouse(this)[0] + 30) + "px")
.style("top", (d3.mouse(this)[1] + 30) + "px");
}
let moveTooltip = function(d) {
tooltip
.style("left", (d3.mouse(this)[0] + 30) + "px")
.style("top", (d3.mouse(this)[1] + 30) + "px");
}
let hideTooltip = function(d) {
tooltip
.transition()
.duration(200)
.style("opacity", 0);
}
//////////////
let node = svg.selectAll(".node")
.data(root.children)
.enter()
.append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
node.append("title")
.text(function(d) {
return d.data.className + ": " + format(d.data.value);
});
node.append("circle")
.attr("r", function(d) {
return d.r;
})
.style("fill", function(d) {
return d.data.color;
})
.style("stroke", "none")
// trigger tooltip functions
.on("mouseover", showTooltip)
.on("mousemove", moveTooltip)
.on("mouseleave", hideTooltip);
node.append("text")
.attr("dy", "0.3em")
.style("text-anchor", "middle")
.text(function(d) {
return d.data.className.substring(0, d.r / 3.8);
});
});
function classes(root) {
let classes = [];
function recurse(name, node) {
if (node.children) {
node.children.forEach(function(child) {
recurse(node.name, child);
});
} else {
classes.push({
packageName: name,
className: node.name,
value: node.size,
color: node.color
});
}
}
recurse(null, root);
return {
children: classes
};
}
d3.select(self.frameElement)
.style("height", diameter + "px");
});
Here is a fiddle that I just made using the code from the blocks and the tooltip.
There were a couple of errors in the code that you entered.
The tooltip div was being appended to the SVG and that is incorrect, an SVG can't contain a `div', changing it to:
var tooltip = d3.select('body')
.append("div")
.style("opacity", 0)
made the tooltip working.
Then, there was missing the position: absolute in the tooltip style
And finally, the left and top styles in the tooltip, were based only on the bubble, so I added the translation to those coordinates doing something like:
.style("left", (d.x + (d3.mouse(this)[0] + 30)) + "px")
.style("top", (d.y + (d3.mouse(this)[1] + 30)) + "px");
I am trying to implement the FishEye lens (Cartesian) in my scatterplot.
I am trying to follow this approach, but apparently my selector already fails.
I have my FishEye defined as
var fisheye = d3.fisheye.circular().radius(120);
svg.on("mousemove", function() {
fisheye.focus(d3.mouse(this));
console.log("here " + points.selectAll("circle").length);
points.selectAll("circle").each(function(d) {
console.log("aaa");
d.fisheye = fisheye(d);
/*points.selectAll("circle")
.each(function(d) {
console.log("???");
this.attr("cx", function(d) { return d.fisheye.x; })
this.attr("cy", function(d) { return d.fisheye.y; })
this.attr("r", function(d) { console.log("hype"); return 10; });
}); */
});
});
and my points is defined as
points = svg.append("g")
.attr("class", "point")
.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d) { // Set the x position using the x-scale
return x(d.x);
})
.attr("cy", function(d) { // Set the y position using the y-scale
return y(d.y);
})
.attr("r", 5) // Set the radius of every point to 5
.on("mouseover", function(d) { // On mouse over show and set the tooltip
if(!isBrushing){
tooltip.transition()
.duration(200)
.style("opacity", 0.9);
tooltip.html(d.symbol + "<br/> (" + parseFloat(x(d.x)).toFixed(4)
+ ", " + parseFloat(y(d.y)).toFixed(4) + ")")
.style("left", (d3.event.pageX + 5) + "px")
.style("top", (d3.event.pageY - 28) + "px");
}
})
.on("mouseout", function(d) { // on mouseout, hide the tooltip.
tooltip.transition()
.duration(500)
.style("opacity", 0);
});
The console.log with "here" is spamming when I am moving the mouse, and shows the correct amount. Hwoever, the each loop is never executed as I do not see "aaa". I have also tried to just use selectAll("circle") but that doesn't work either.
What am I doing wrong and how can I get my FishEye to work?
I have a bar chart and I have text values at the end of each bar. What I would like to do is set text to invisible, and on mouseover I'd like it to show the number associated with the bar, at the magnitude of that bar. I'm having trouble figuring out how to do this in an efficient manner.
var tooltip = d3.select("body").append("div")
.style("position", "absolute")
.attr("class", "tooltip")
.style("opacity", 0);
var rect = svg.selectAll("rect")
.attr("class", "rect")
.data(dataset)
.enter()
.append("rect")
.attr("y", function(d,i){
return yScale(i);
})
.attr("x", 0)
.attr("width", function(d,i){
return xScale(d);
})
.attr("height", h/dataset.length)
.style("fill", function(d,i){
return colors(d);
})
.on("mouseover", function(d){
d3.select(this).style("opacity", 0.5)
tooltip.transition()
.duration(200)
.style("opacity", 1);
tooltip.html(d)
.style("left", d3.event.pageX + "px")
.style("top", d3.event.pageY + "px")
})
.on("mouseout", function(d){
d3.select(this).style("opacity", 1)
tooltip.transition()
.duration(500)
.style("opacity", 0)
});
Instead of mouseover and mouseout, I recommend doing it with $(this).hover and $(this).mousemove. Try something like this:
$(this).hover(
function() {
tooltip.transition()
.duration(200)
.style("opacity", 1)
// In order to trigger the magnitude or 'width' of the rect:
var rectWidth = $(this).attr("width");
}, function () {
tooltip.transition()
.duration(500)
.style("opacity", 1e-6)
}
);
/*$(this).mousemove(function(event) {
tooltip
.style("left", event.clientX + "px")
.style("top", event.clientY + "px")
});*/
I have an issue and I really need your help.
I have a realtime graph with a vertical bar that moves with cursor and i want it to show the value of the graph (d.time and d.value) when the cursor points to. http://jsfiddle.net/QBDGB/54/ i have two series of data (data1s and data2s) that is generated randomly and I put the time in which the data is generated in "time" variable as you can see:
now = new Date(Date.now() - duration);
var data1 = initialise();
var data2 = initialise();
//Make stacked data
var data1s = data1;
var data2s = [];
for(var i = 0; i < data1s.length; i++){
data2s.push({
value: data1s[i].value + data2[i].value,
time: data2[i].time
}
)};
function initialise() {
var arr = [];
for (var i = 0; i < n; i++) {
var obj = {
time: Date.now(),
value: Math.floor(Math.random() * 100)
};
arr.push(obj);
}
return arr;
}
When I hover around the graph I want the tooltip show the time and value but it does not recognize it and show "undefined" since I do not know how to pass my datasets (data1s and data2s) so "mouseover function can recognize which data to show! This is how the tooltip functions are made and call from "path1" and "path2".
function mouseover() {
div.transition()
.duration(500)
.style("opacity", 1);
}
function mousemove(d) {
div
.text( d.time+ ", " + d.value)
.style("left", (d3.event.pageX ) + "px")
.style("top", (d3.event.pageY ) + "px");
}
function mouseout() {
div.transition()
.duration(500)
.style("opacity", 1e-6);
}
var path1 = svg.append("g")
.attr("clip-path", "url(#clip)")
.append("path")
.data([data1s])
.attr("class", "line1")
.on("mouseover", mouseover)
.on("mousemove", mousemove)
.on("mouseout", mouseout);
var path2 =svg.append("g")
.attr("clip-path", "url(#clip)")
.append("path")
.data([data2s])
.attr("class", "line2")
.on("mouseover", mouseover)
.on("mousemove", mousemove)
.on("mouseout", mouseout);
Do you have any idea of what to do? i think i need to add
svg.selectAll("path1")
.attr("opacity", 1)
or svg.selectAll("datas1")
.attr("opacity", 1)
Somewhere! but i do not know how..
Thank you,
Update your mouseover function as:
function mousemove(d) {
div
.text( d[0].time+ ", " + d[0].value)
.style("left", (d3.event.pageX ) + "px")
.style("top", (d3.event.pageY ) + "px");
}
Include the index to the object 'd'.
Hope that helps.