I am using D3 JavaScript library to display data as a force directed marker. It works fine. But I am unable to add click event to the circle. so when I click on the circle, I get detailed analysis of the circle and display it in a modal box.
var links = [{source: "x", target:"y", type: "paid"},......]';
var nodes = {};
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
});
var w = 950,
h = 500;
var force = d3.layout.force()
.nodes(d3.values(nodes))
.links(links)
.size([w, h])
.linkDistance(60)
.charge(-300)
.on("tick", tick)
.start();
var svg = d3.select("#graph").append("svg:svg")
.attr("width", w)
.attr("height", h);
// Per-type markers, as they don't inherit styles.
svg.append("svg:defs").selectAll("marker")
.data(["suit", "licensing", "resolved"])
.enter().append("svg:marker")
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5");
var path = svg.append("svg:g").selectAll("path")
.data(force.links())
.enter().append("svg:path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" + d.type + ")"; });
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle")
.attr("r", 6)
.call(force.drag);
var text = svg.append("svg:g").selectAll("g")
.data(force.nodes())
.enter().append("svg:g");
// A copy of the text with a thick white stroke for legibility.
text.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.attr("class", "shadow")
.text(function(d) { return d.name; });
text.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.text(function(d) { return d.name; });
// Use elliptical arc path segments to doubly-encode directionality.
function tick() {
path.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
circle.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
text.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
I tried adding .on("click", 'alert(\'Hello world\')') to var circle. It does not work as expected. It alerts on load instead on click.
I appreciate any help
Try this:
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle")
.attr("r", 6)
.on("click", function(d,i) { alert("Hello world"); })
.call(force.drag);
Try out this, if you want the node contained within the circle (let's say that your nodes are mapping an object with a key called anger and a value 34:
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle")
.attr("r", 6)
.on("click", function(d,i) { alert(d.anger); }) // this will alert 34
.call(force.drag);
Or try this for the attributes of the svg (getting the radius of the svg, for example):
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle")
.attr("r", 6)
.on("click", function(d,i) { alert(d3.select(this).r; }) // this will print out the radius })
.call(force.drag);
Sorry if my post is like the one above, but I thought the clarification could be useful.
Related
I was trying to retrieve nodes and links from a python code that already has them unique and in the form of a JSON but while the console.log shows up the data on the browser am unable to view them as a forcelayout graph on the screen. Presumably i dont understand the sequence of calling here in javascript so bear with my lack of javascript knowledge. Any help here is much appreciated.
This is a borrowed example from the gallery of course with me tampering the d3.json piece.
<script>
var width = 960,
height = 500;
//force = d3.layout.force().nodes(d3.values(ailments)).links(rels).size([width, height]).linkDistance(60).charge(-300).on("tick", tick).start();
var nodes = {};
var ailments = {} ;
var rels = [];
var force = d3.layout.force().size([width, height]).linkDistance(60).charge(-300).on("tick",tick);
console.log('initiated force!! be with you !!');
d3.json("/getA", function(error, dataset){
console.log('getA the function gets called now ... ');
ailments = dataset.nodes;
//ailments = dataset.nodes['nodes'];
//rels = dataset.links['links'] ;
rels = dataset.links;
console.log(ailments);
//console.log(nodes);
console.log('relationships coming up..');
console.log(rels);
force.start();
});
function tick() {
path.attr("d", linkArc);
circle.attr("transform", transform);
text.attr("transform", transform);
}
force = d3.layout.force().nodes(d3.values(ailments)).links(rels).size([width, height]).linkDistance(60).charge(-300).on("tick", tick).start();
console.log("now i threw the graph out there");
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("defs").selectAll("marker")
.data(["suit", "licensing", "resolved"])
.enter().append("marker")
.attr("id", function(d) { return d; })
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.attr("stroke", "black")
.append("path")
.attr("d", "M0,-5L10,0L0,5");
// Per-type markers, as they don't inherit styles.
// Use elliptical arc path segments to doubly-encode directionality.
var path = svg.append("g").selectAll("path")
.data(force.links())
.enter().append("path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" + d.type + ")"; });
var circle = svg.append("g").selectAll("circle")
.data(force.nodes())
.enter().append("circle")
.attr("r", 6)
.call(force.drag);
var text = svg.append("g").selectAll("text")
.data(force.nodes())
.enter().append("text")
.attr("x", 8)
.attr("y", ".31em")
.text(function(d) { return d.name; });
function linkArc(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
}
function transform(d) {
return "translate(" + d.x + "," + d.y + ")";
}
</script>
as i said i am still unclear on the sequence here as this is my first ever javascript attempt!
Noticed that python and flask tags were removed - which i think is fine because i dont think there is an issue with the below python code that's sending this data. just FYI
#app.route("/getA")
def getA():
print('get A gets called ...')
db = get_db()
nodes = []
rels = []
ailment = []
cure = []
jlinks = {"links":[]}
uniqueNodes = {"nodes":[]}
sql = "MATCH (a:Ailment) -[:SOLVED_BY]->(theCURE) return a as ailment, theCURE limit 5"
with db as graphDB_Session:
nodes = graphDB_Session.run(sql)
print("output:")
for node in nodes:
#print(node)
prepare_links(node, ailment, cure)
for idx, value in enumerate(ailment):
#print (ailment[idx], cure[idx])
source = ailment[idx]['title']
target = cure[idx]['title']
y = {"source":source, "target":target, "type":"SOLVED_BY"}
jlinks["links"].append(y)
if (source not in (uniqueNodes["nodes"])):
uniqueNodes["nodes"].append(source)
if (target not in (uniqueNodes["nodes"])):
uniqueNodes["nodes"].append(target)
print(jlinks)
print(uniqueNodes)
return Response(dumps({"nodes": uniqueNodes, "links": jlinks}),mimetype="application/json")
def serialize_ailment(ailment):
return {
"title":ailment["title"]
}
def serialize_cure(cure):
return {
"title":cure["title"]
}
def prepare_links(node, ailment, cure):
#ailment.append(serialize_ailment(node.value("ailment")))
ailment.append(node.value("ailment"))
#cure.append(serialize_cure(node.value("theCURE")))
cure.append(node.value("theCURE"))
Bear with some unwanted code, comments as i've basically tried out a few variants.
Two mistakes ... i figured ...
The sequence of calling - as i mentioned above had to be fixed by rolling the forcelayout calls from within the .json function
The approach to getting an array from the API call into another array object here in Javascript was also messed up. Specifically this line -
rels = dataset.links["links"];
looks very obvious but somehow i'd messed this up as well. The updated script that works on my own data finally goes like this -
d3.json("/getA", function(error, dataset){
console.log('getA the function gets called now ... ');
ailments = dataset.nodes;
rels = dataset.links["links"];
console.log(ailments);
//console.log(nodes);
console.log('relationships coming up..');
console.log(rels);
//links = [dataset.links];
rels.forEach(function(dink) {
dink.source = nodes[dink.source] || (nodes[dink.source] = {name: dink.source});
dink.target = nodes[dink.target] || (nodes[dink.target] = {name: dink.target});
console.log('creating unique nodes gets called again');
});
console.log('relationships again ..');
console.log(rels);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("defs").selectAll("marker")
.data(["suit", "licensing", "resolved"])
.enter().append("marker")
.attr("id", function(d) { return d; })
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.attr("stroke", "black")
.append("path")
.attr("d", "M0,-5L10,0L0,5");
var force = d3.layout.force().nodes(d3.values(nodes)).links(rels).size([width, height]).linkDistance(60).charge(-300).on("tick", tick).start();
console.log('graph goes up only now');
force.on("tick", function(e) {
path.attr("d", linkArc);
circle.attr("transform", transform);
text.attr("transform", transform);
});
var text = svg.append("g").selectAll("text")
.data(force.nodes())
.enter().append("text")
.attr("x", 8)
.attr("y", ".31em")
.text(function(d) { return d.name; });
var path = svg.append("g").selectAll("path")
.data(force.links())
.enter().append("path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" + d.type + ")"; });
var circle = svg.append("g").selectAll("circle")
.data(force.nodes())
.enter().append("circle")
.attr("r", 6)
.call(force.drag);
circle.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
And the python code that "serves up" this data goes like this ...
#app.route("/getA")
def getA():
print('get A gets called ...')
db = get_db()
nodes = []
ailment = []
cure = []
jlinks = {"links":[]}
uniqueNodes = {"nodes":[]}
sql = "MATCH (a:Ailment) -[:SOLVED_BY]->(theCURE) return a as ailment, theCURE limit 5"
with db as graphDB_Session:
nodes = graphDB_Session.run(sql)
print("output:")
for node in nodes:
#print(node)
prepare_links(node, ailment, cure)
counter = 0
for idx, value in enumerate(ailment):
source = ailment[idx]['title']
target = cure[idx]['title']
y = {"source":str(source), "target":str(target), "type":"SOLVED_BY"}
jlinks["links"].append(y)
if source not in uniqueNodes["nodes"]:
uniqueNodes["nodes"].append(source)
if target not in uniqueNodes["nodes"]:
uniqueNodes["nodes"].append(target)
print(jlinks)
print(uniqueNodes)
return Response(dumps({"nodes": uniqueNodes, "links": jlinks}),mimetype="application/json")
Technicalily i haven't yet used up the unique nodes coming from the python function but that's for another day :) thanks for reading.
I am following this example: http://bl.ocks.org/mbostock/1153292
I have row upon row of JSON data that looks like this:
{"source":"Michael Scott","target":"Jim Halpert","type":"pro"},
{"source":"Jim Halpert","target":"Dwight Schrute","type":"pro"}
Current code to render this data looks like this:
var links = [
{"source":"Michael Scott","target":"Jim Halpert","type":"pro"},
{"source":"Jim Halpert","target":"Dwight Schrute","type":"pro"}
];
var nodes = {};
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
});
var width = 2000,
height = 1000;
var force = d3.layout.force()
.nodes(d3.values(nodes))
.links(links)
.size([width, height])
.linkDistance(60)
.charge(-300)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("defs").selectAll("marker")
.data(["pro"])
.enter().append("marker")
.attr("id", function(d) { return d; })
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5");
var path = svg.append("g").selectAll("path")
.data(force.links())
.enter().append("path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" + d.type + ")"; });
var circle = svg.append("g").selectAll("circle")
.data(force.nodes())
.enter().append("circle")
.attr("r", 6)
.call(force.drag);
var text = svg.append("g").selectAll("text")
.data(force.nodes())
.enter().append("text")
.attr("x", 8)
.attr("y", ".31em")
.text(function(d) { return d.name; });
function tick() {
path.attr("d", linkArc);
circle.attr("transform", transform);
text.attr("transform", transform);
}
function linkArc(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
}
function transform(d) {
return "translate(" + d.x + "," + d.y + ")";
}
</script>
How do I call the data from an external data.json file? I've looked at all the other related SO questions and other D3 examples, but I haven't been able to get anything to work.
I've tried (and then changing all references to links to data):
d3.json("data.json", function(error, data) {
});
Here is that full code:
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
d3.json("data.json", function(error, data) {
});
var nodes = {};
data.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
});
var width = 2000,
height = 1000;
var force = d3.layout.force()
.nodes(d3.values(nodes))
.data(data)
.size([width, height])
.linkDistance(60)
.charge(-300)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("defs").selectAll("marker")
.data(["pro"])
.enter().append("marker")
.attr("id", function(d) { return d; })
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5");
var path = svg.append("g").selectAll("path")
.data(force.data())
.enter().append("path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" + d.type + ")"; });
var circle = svg.append("g").selectAll("circle")
.data(force.nodes())
.enter().append("circle")
.attr("r", 6)
.call(force.drag);
var text = svg.append("g").selectAll("text")
.data(force.nodes())
.enter().append("text")
.attr("x", 8)
.attr("y", ".31em")
.text(function(d) { return d.name; });
function tick() {
path.attr("d", linkArc);
circle.attr("transform", transform);
text.attr("transform", transform);
}
function linkArc(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
}
function transform(d) {
return "translate(" + d.x + "," + d.y + ")";
}
</script>
This results in the error Uncaught Reference Error: "data" is not defined for this line data.forEach(function(link) {. data.json is located in the same directory as index.html
I've tried various other implementations as well that I picked up from other D3 examples on blocks.org. Any and all insight would be greatly appreciated. Please let me know if there's anything I can do to improve my question!
Here is a working example with your data. You need to do a couple of things to make it work with an external json file.
Make sure you include all your code inside your d3.json call.
Since we're using the variable links to hold all our data, you need to set that equal to data which is returned from the d3.json call.
Check working code below:
var data_url = "https://api.myjson.com/bins/10kk91";
d3.json(data_url, function(error, data){
var links = data; //set links equal to data which is returned from d3.json
var nodes = {};
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
});
var width = 960,
height = 500;
var force = d3.layout.force()
.nodes(d3.values(nodes))
.links(links)
.size([width, height])
.linkDistance(60)
.charge(-300)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// Per-type markers, as they don't inherit styles.
svg.append("defs").selectAll("marker")
.data(["suit", "licensing", "resolved"])
.enter().append("marker")
.attr("id", function(d) { return d; })
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5");
var path = svg.append("g").selectAll("path")
.data(force.links())
.enter().append("path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" + d.type + ")"; });
var circle = svg.append("g").selectAll("circle")
.data(force.nodes())
.enter().append("circle")
.attr("r", 6)
.call(force.drag);
var text = svg.append("g").selectAll("text")
.data(force.nodes())
.enter().append("text")
.attr("x", 8)
.attr("y", ".31em")
.text(function(d) { return d.name; });
// Use elliptical arc path segments to doubly-encode directionality.
function tick() {
path.attr("d", linkArc);
circle.attr("transform", transform);
text.attr("transform", transform);
}
function linkArc(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
}
function transform(d) {
return "translate(" + d.x + "," + d.y + ")";
}
}); //end d3.json call
.link {
fill: none;
stroke: #666;
stroke-width: 1.5px;
}
#licensing {
fill: green;
}
.link.licensing {
stroke: green;
}
.link.resolved {
stroke-dasharray: 0,2 1;
}
circle {
fill: #ccc;
stroke: #333;
stroke-width: 1.5px;
}
text {
font: 10px sans-serif;
pointer-events: none;
text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
I am trying to plot a network graph using networkD3 in R. I wanted to make some changes to the display so that the text labels (which appears when mouseover) can be easily read.
Please refer to the link here for an example. Note: Jump to the d3ForceNetwork plot.
As seen in the example, the labels are hard to read due to its colour and it often gets obstructed by the surrounding nodes. I have been messing around with the JS file and managed to change the text label color to black. However, having no knowledge of JS or CSS (I can't even tell the difference between the 2 actually), I have no idea how I can change the stack order such that the text labels will always be displayed above any other objects.
Can anyone advise me on how I can achieve the desired outcome?
Below is the full JS file:
HTMLWidgets.widget({
name: "forceNetwork",
type: "output",
initialize: function(el, width, height) {
d3.select(el).append("svg")
.attr("width", width)
.attr("height", height);
return d3.layout.force();
},
resize: function(el, width, height, force) {
d3.select(el).select("svg")
.attr("width", width)
.attr("height", height);
force.size([width, height]).resume();
},
renderValue: function(el, x, force) {
// Compute the node radius using the javascript math expression specified
function nodeSize(d) {
if(options.nodesize){
return eval(options.radiusCalculation);
}else{
return 6}
}
// alias options
var options = x.options;
// convert links and nodes data frames to d3 friendly format
var links = HTMLWidgets.dataframeToD3(x.links);
var nodes = HTMLWidgets.dataframeToD3(x.nodes);
// get the width and height
var width = el.offsetWidth;
var height = el.offsetHeight;
var color = eval(options.colourScale);
// set this up even if zoom = F
var zoom = d3.behavior.zoom();
// create d3 force layout
force
.nodes(d3.values(nodes))
.links(links)
.size([width, height])
.linkDistance(options.linkDistance)
.charge(options.charge)
.on("tick", tick)
.start();
// thanks http://plnkr.co/edit/cxLlvIlmo1Y6vJyPs6N9?p=preview
// http://stackoverflow.com/questions/22924253/adding-pan-zoom-to-d3js-force-directed
var drag = force.drag()
.on("dragstart", dragstart)
// allow force drag to work with pan/zoom drag
function dragstart(d) {
d3.event.sourceEvent.preventDefault();
d3.event.sourceEvent.stopPropagation();
}
// select the svg element and remove existing children
var svg = d3.select(el).select("svg");
svg.selectAll("*").remove();
// add two g layers; the first will be zoom target if zoom = T
// fine to have two g layers even if zoom = F
svg = svg
.append("g").attr("class","zoom-layer")
.append("g")
// add zooming if requested
if (options.zoom) {
function redraw() {
d3.select(el).select(".zoom-layer").attr("transform",
"translate(" + d3.event.translate + ")"+
" scale(" + d3.event.scale + ")");
}
zoom.on("zoom", redraw)
d3.select(el).select("svg")
.attr("pointer-events", "all")
.call(zoom);
} else {
zoom.on("zoom", null);
}
// draw links
var link = svg.selectAll(".link")
.data(force.links())
.enter().append("line")
.attr("class", "link")
.style("stroke", function(d) { return d.colour ; })
//.style("stroke", options.linkColour)
.style("opacity", options.opacity)
.style("stroke-width", eval("(" + options.linkWidth + ")"))
.on("mouseover", function(d) {
d3.select(this)
.style("opacity", 1);
})
.on("mouseout", function(d) {
d3.select(this)
.style("opacity", options.opacity);
});
// draw nodes
var node = svg.selectAll(".node")
.data(force.nodes())
.enter().append("g")
.attr("class", "node")
.style("fill", function(d) { return color(d.group); })
.style("opacity", options.opacity)
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.on("click", click)
.call(force.drag);
node.append("circle")
.attr("r", function(d){return nodeSize(d);})
.style("stroke", "#fff")
.style("opacity", options.opacity)
.style("stroke-width", "1.5px");
node.append("svg:text")
.attr("class", "nodetext")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name })
.style("font", options.fontSize + "px " + options.fontFamily)
.style("opacity", options.opacityNoHover)
.style("pointer-events", "none");
function tick() {
node.attr("transform", function(d) {
if(options.bounded){ // adds bounding box
d.x = Math.max(nodeSize(d), Math.min(width - nodeSize(d), d.x));
d.y = Math.max(nodeSize(d), Math.min(height - nodeSize(d), d.y));
}
return "translate(" + d.x + "," + d.y + ")"});
link
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
}
function mouseover() {
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", function(d){return nodeSize(d)+5;});
d3.select(this).select("text").transition()
.duration(750)
.attr("x", 13)
.style("stroke-width", ".5px")
.style("font", options.clickTextSize + "px ")
.style('fill', 'black')
.style('position','relative')
.style("opacity", 1);
}
function mouseout() {
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", function(d){return nodeSize(d);});
d3.select(this).select("text").transition()
.duration(1250)
.attr("x", 0)
.style("font", options.fontSize + "px ")
.style("opacity", options.opacityNoHover);
}
function click(d) {
return eval(options.clickAction)
}
// add legend option
if(options.legend){
var legendRectSize = 18;
var legendSpacing = 4;
var legend = svg.selectAll('.legend')
.data(color.domain())
.enter()
.append('g')
.attr('class', 'legend')
.attr('transform', function(d, i) {
var height = legendRectSize + legendSpacing;
var offset = height * color.domain().length / 2;
var horz = legendRectSize;
var vert = i * height+4;
return 'translate(' + horz + ',' + vert + ')';
});
legend.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style('fill', color)
.style('stroke', color);
legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.style('fill', 'darkOrange')
.text(function(d) { return d; });
}
// make font-family consistent across all elements
d3.select(el).selectAll('text').style('font-family', options.fontFamily);
},
});
I suspect I need to make some changes to the code over here:
function mouseover() {
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", function(d){return nodeSize(d)+5;});
d3.select(this).select("text").transition()
.duration(750)
.attr("x", 13)
.style("stroke-width", ".5px")
.style("font", options.clickTextSize + "px ")
.style('fill', 'black')
.style("opacity", 1);
}
You need to resort the node groups holding the circles and text so the currently mouseover'ed one is the last in that group, and thus the last one drawn so it appears on top of the others. See the first answer here -->
Updating SVG Element Z-Index With D3
In your case, if your data doesn't have an id field you may have to use 'name' instead as below (adapted to use the mouseover function you've got):
function mouseover(d) {
d3.selectAll("g.node").sort(function (a, b) {
if (a.name != d.name) return -1; // a is not the hovered element, send "a" to the back
else return 1; // a is the hovered element, bring "a" to the front (by making it last)
});
// your code continues
The pain might be that you have to do this edit for every d3 graph generated by this R script, unless you can edit the R code/package itself. (or you could suggest it to the package author as an enhancement.)
To start I'm sure there is a much simpler way to do this then what I'm trying to do. I'm trying to zoom in on specific circles using d3js and have text overlaying the circle. The problem is that since the text is ontop of the circle the text blocks the onclick even that is fired when you click on the circle. Here is my code so far:
js
var svg = d3.select("svg")
.attr("width", width)
.attr("height", height)
.append("g");
var node1 = svg.append("g")
.append("circle")
.data([offset[0]])
.text(function(d){return d.label})
.attr("r", 25)
.style("fill","white")
.on("click", clicked);
node1.attr("cx", 530)
.attr("cy", 310)
.transition()
.delay(500)
.duration(1000)
.attr("r", 55)
.attr("cx", 530)
.attr("cy", 205);
d3.select('g').append('text')
.attr("id","orient")
.attr("dx", 510)
.attr("dy", 210)
.attr("width", 90)
.attr("height", 90)
.text(function(d){return offset[0].label});
var node2 = svg.append("g")
.append("circle")
.data([offset[1]])
.attr("r", 25)
.style("fill","white")
.on("click", clicked);
node2.attr("cx", 530)
.attr("cy", 310)
.transition()
.delay(500)
.duration(1000)
.attr("r", 55)
.attr("cx", 620)
.attr("cy", 310);
d3.select('g').append('text')
.attr("id","seperate")
.attr("dx", 590)
.attr("dy", 315)
.attr("width", 90)
.attr("height", 90)
.text(function(d){return offset[1].label});
function
function clicked(d) {
var imageSelected = this;
console.log("clicked");
var cx, cy, k, offset;
var setClass = d.swipe_class;
cx = d3.select(this).attr("cx");
cy = d3.select(this).attr("cy");
k = 2;
cx= cx - d.xoff;
cy= cy - d.yoff;
console.log("cy="+d.yoff +"cx="+ d.xoff);
svg.transition()
.duration(750)
.attr("transform", "translate(" + width/2 + "," + height/2 + ")scale(" + k + ")translate(" + -cx + "," + -cy + ")");
}
Is there a way to trigger the circles click event when I click the text ontop of it? Or maybe just a better way of doing this that would allow it?
You can set the text to ignore pointer events:
...
.append("text")
.attr("pointer-events", "none")
...
New to d3 and trying to develop a force directed tree into which we can plug varioss dataset. I've managed to get the basic idea up and running but would like to make the links curved so I can deal with multiple links. I've looked at http://bl.ocks.org/1153292 and I'm just not getting it. The nearest I get is it all working with no path visible. This is my code for straight lines, I'd appreciate some help if you've got the time
Thanks:
//Sets up the svg that holds the data structure and puts it in the div called mapBox
var svg = d3.select("div#mapBox.theMap").append("svg")
.attr("width", mapWidth)
.attr("height", mapHeight);
//Sets up the data structure and binds the data to it
var force = d3.layout.force()
.nodes(data.nodes)
.links(data.links)
.size([mapWidth, mapHeight])
.charge(-600)
.linkDistance(60)
.start();
//Draws the links and set up their styles
var link = svg.selectAll("link")
.data(data.links)
.enter().append("line")
.attr("class", "link")
.style("stroke", "#ccc")
//Creates nodes and attached "g" element to append other things to
var node = svg.selectAll(".node")
.data(data.nodes)
.enter().append("g")
.call(force.drag);
//Appends the cirdle to the "g" element and defines styles
node.append("circle")
.attr("r", function(d) { if (d.weight<1.1) {return 5} else {return d.weight*1.3+5 }})
.style("fill", "White")
.style("stroke-width", 3)
.style("stroke", function(d) { if (d.type==1) {return "#eda45e "} if(d.type==2) {return "#819e9a"}else {return "#c36256" }} ) // Node stroke colors
.on("mouseover", nodeMouseover)
on("mouseout", nodeMouseout)
.on("mousedown", nodeMousedown)
.call(force.drag);
//Appends text to the "g" element and defines styles
node.append("text")
.attr("class", "nodetext")
.attr("dx", 16)
.attr("dy", ".35em")
.attr("text-anchor", function(d) { if (d.type==1) {return "middle";} else {return "start";} })
.text(function(d) { return d.name })
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});
Der, worked it out.
change
.enter().append("line")
to
.enter().append("path")
then change
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
to
link.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
Hope that help anyone stuck as I was
This also worked for me.
First define a path:
var path = vis.selectAll("path")
.data(force.links());
path.enter().insert("svg:path")
.attr("class", "link")
.style("stroke", "#ccc");
Then define the curve, as Bob Haslett says and in the Mobile Patent Suits example:
path.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});