Force + Drag + Zoom : freeze after few seconds - javascript

First, I'm quite new in D3.
I'm trying to implement different behaviors in a single D3 graph, using these examples :
Drag + Zoom
Force-directed Graph
But my graph freezes after few seconds and I don't understand why...
Here is my code : http://jsfiddle.net/blt909/aVhd8/20/ [WORKING FINE VERSION]
var margin = {top: -5, right: -5, bottom: -5, left: -5};
var width = 500 - margin.left - margin.right,
height = 400- margin.top - margin.bottom;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-200)
.linkDistance(50)
.size([width + margin.left + margin.right, height + margin.top + margin.bottom]);
var zoom = d3.behavior.zoom()
.scaleExtent([1, 10])
.on("zoom", zoomed);
var drag = d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", dragstarted)
.on("drag", dragged)
.on("dragend", dragended);
var svg = d3.select("#map").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.right + ")")
.call(zoom);
var rect = svg.append("rect")
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all");
var container = svg.append("g");
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var tooltip = d3.select("body")
.append("foreignObject")
.append("xhtml:div")
.attr("id", "tooltip")
.style("position", "absolute")
.style("z-index", "10")
.style("color", "#eeeeee")
.style("visibility", "hidden")
.text("");
var link = container.append("g")
.attr("class", "links")
.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = container.append("g")
.attr("class", "nodes")
.selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.call(drag);
node.append("circle")
.attr("r", function(d) { return d.weight * 2+ 12; })
.style("fill", function(d) { return color(1/d.rating); });
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 + ")"; });
});
var linkedByIndex = {};
graph.links.forEach(function(d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
function isConnected(a, b) {
return linkedByIndex[a.index + "," + b.index] || linkedByIndex[b.index + "," + a.index];
}
node.on("mouseover", function(d){
node.classed("node-active", function(o) {
thisOpacity = isConnected(d, o) ? true : false;
this.setAttribute('fill-opacity', thisOpacity);
return thisOpacity;
});
link.classed("link-active", function(o) {
return o.source === d || o.target === d ? true : false;
});
d3.select(this).classed("node-active", true);
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", (d.weight * 2+ 12)*1.5);
})
.on("mouseout", function(d){
node.classed("node-active", false);
link.classed("link-active", false);
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", d.weight * 2+ 12);
});
function dottype(d) {
d.x = +d.x;
d.y = +d.y;
return d;
}
function zoomed() {
container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
d3.select(this).classed("dragging", true);
//ADDING force.start(); HERE SOLVES THE ISSUE
force.start();
}
function dragged(d) {
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}
function dragended(d) {
d3.select(this).classed("dragging", false);
}
Thanks for your help

Putting force.start(); inside dragstarted function stops freezing.
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
d3.select(this).classed("dragging", true);
force.start();
};
Here is fiddle

Related

How can I drag group (g) element in D3.js?

I want to make a draggable <g> element containing a <circle> and a <text> but I failed.
Now I have this code:
var margin = {top: -5, right: -5, bottom: -5, left: -5},
width = 1960 - margin.left - margin.right,
height = 1500 - margin.top - margin.bottom;
var drag = d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", dragstarted)
.on("drag", dragged)
.on("dragend", dragended);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
var dotContainer = svg.append("g")
.attr("class", "dotContainer")
.datum({x:220, y:120})
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; })
.call(drag);
var dot = dotContainer.append("circle")
.attr("class", "dot")
.datum({x:220, y:120})
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 5).call(drag);
var text = dotContainer.append("text")
.datum({x:220, y:120})
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; })
.text('Title');
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
d3.select(this).classed("dragging", true);
}
function dragged(d) {
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}
function dragended(d) {
d3.select(this).classed("dragging", false);
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<circle> element is perfectly draggable, ok. But I need to apply dragging to the whole <g> element to drag my circle together with the <text> element.
How can I do this?
When I apply call(drag) to dotContainer like this
dotContainer.call(drag);
then nothing works.
You should rewrite your dotContainer variable this way:
var dotContainer = svg.append("g")
.attr("class", "dotContainer")
.datum({x:220, y:120})
.attr("transform", function(d) { return 'translate(' + d.x + ' '+ d.y + ')'; })
.call(drag);
Remove .call(drag) for dot variable and rewrite dragged function like this:
function dragged(d) {
d.x += d3.event.dx;
d.y += d3.event.dy;
d3.select(this).attr("transform", function(d,i){
return "translate(" + [ d.x,d.y ] + ")"
});
}
Thus we use transform attribute for an initial container position and for the position update during the dragging.
Check demo in the hidden snippet:
var margin = {top: -5, right: -5, bottom: -5, left: -5},
width = 1960 - margin.left - margin.right,
height = 1500 - margin.top - margin.bottom;
var drag = d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", dragstarted)
.on("drag", dragged)
.on("dragend", dragended);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
var dotContainer = svg.append("g")
.attr("class", "dotContainer")
.datum({x:20, y:20})
.attr("transform", function(d) { return 'translate(' + d.x + ' '+ d.y + ')'; })
.call(drag);
var dot = dotContainer.append("circle")
.attr("class", "dot")
.datum({x:20, y:20})
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 5)
var text = dotContainer.append("text")
.datum({x:20, y:20})
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; })
.text('Title');
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
d3.select(this).classed("dragging", true);
}
function dragged(d) {
d.x += d3.event.dx;
d.y += d3.event.dy;
d3.select(this).attr("transform", function(d,i){
return "translate(" + [ d.x,d.y ] + ")"
});
}
function dragended(d) {
d3.select(this).classed("dragging", false);
}
.dotContainer {
cursor: move;
}
<script src="https://d3js.org/d3.v3.min.js"></script>

upgrading d3js from v3 to v4 causes zoom problems

I'm using d3js v3, and I want to upgrade to v4, but upgrading to v4 causes zoom to be undefined
here's the code :
var zoom = d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoomed);
Error as shown in the console :
index.html:192 Uncaught TypeError: Cannot read property 'zoom' of undefined
I used this example as a reference to my implementation :
https://bl.ocks.org/mbostock/6123708
The code # Github pages :
http://jmargieh.github.io/NBA-shots-chart-d3js/
Thanks for the help.
Try this, somethings have been renamed thats all.
var margin = {top: -5, right: -5, bottom: -5, left: -5},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var zoom = d3.zoom()
.scaleExtent([1, 10])
.on("zoom", zoomed);
var drag = d3.drag()
.subject(function(d) { return d; })
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.right + ")")
.call(zoom);
var rect = svg.append("rect")
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all");
var container = svg.append("g");
container.append("g")
.attr("class", "x axis")
.selectAll("line")
.data(d3.range(0, width, 10))
.enter().append("line")
.attr("x1", function(d) { return d; })
.attr("y1", 0)
.attr("x2", function(d) { return d; })
.attr("y2", height);
container.append("g")
.attr("class", "y axis")
.selectAll("line")
.data(d3.range(0, height, 10))
.enter().append("line")
.attr("x1", 0)
.attr("y1", function(d) { return d; })
.attr("x2", width)
.attr("y2", function(d) { return d; });
d3.tsv("dots.tsv", dottype, function(error, dots) {
dot = container.append("g")
.attr("class", "dot")
.selectAll("circle")
.data(dots)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.call(drag);
});
function dottype(d) {
d.x = +d.x;
d.y = +d.y;
return d;
}
function zoomed() {
container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
d3.select(this).classed("dragging", true);
}
function dragged(d) {
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}
function dragended(d) {
d3.select(this).classed("dragging", false);
}
For zooming v3 vs v5 (which might be the same changes to goto v4), I posted in another related stackoverflow about this if this is useful to people visiting this issue: dagre-d3 js Zoom Fit to all contents

Change cursor on mousedown fails with SVG on Chrome

I'm trying to change the cursor when I drag on a SVG but the cursor change only fires when the mouse button is released. Works perfectly, however, in Firefox.
I'm using Chrome Version 50.0.2661.102 m.
This is the jQuery I'm using:
$('#map')
.mousedown(function(){
$(this).css( 'cursor', 'move' );
})
.mouseup(function(){
$(this).css( 'cursor', 'auto' );
});
BUT the code snippet I added below actually works as it should, yet the fiddle I created doesn't, nor does my actual code on the site I'm building.
How can I do this differently for Chrome so it works always?
var graph = {
"nodes":[
{"name":"1","rating":90,"id":2951},
{"name":"2","rating":80,"id":654654},
{"name":"3","rating":80,"id":6546544},
{"name":"4","rating":1,"id":68987978},
{"name":"5","rating":1,"id":9878933},
{"name":"6","rating":1,"id":6161},
{"name":"7","rating":1,"id":64654},
{"name":"8","rating":20,"id":354654},
{"name":"9","rating":50,"id":8494},
{"name":"10","rating":1,"id":6846874},
{"name":"11","rating":1,"id":5487},
{"name":"12","rating":80,"id":"parfum_kenzo"},
{"name":"13","rating":1,"id":65465465},
{"name":"14","rating":90,"id":"jungle_de_kenzo"},
{"name":"15","rating":20,"id":313514},
{"name":"16","rating":40,"id":36543614},
{"name":"17","rating":100,"id":"Yann_YA645"},
{"name":"18","rating":1,"id":97413},
{"name":"19","rating":1,"id":97414},
{"name":"20","rating":100,"id":976431231},
{"name":"21","rating":1,"id":9416},
{"name":"22","rating":1,"id":998949},
{"name":"23","rating":100,"id":984941},
{"name":"24","rating":100,"id":"99843"},
{"name":"25","rating":1,"id":94915},
{"name":"26","rating":1,"id":913134},
{"name":"27","rating":1,"id":9134371}
],
"links":[
{"source":6,"target":5,"value":6, "label":"publishedOn"},
{"source":8,"target":5,"value":6, "label":"publishedOn"},
{"source":7,"target":1,"value":4, "label":"containsKeyword"},
{"source":8,"target":10,"value":3, "label":"containsKeyword"},
{"source":7,"target":14,"value":4, "label":"publishedBy"},
{"source":8,"target":15,"value":6, "label":"publishedBy"},
{"source":9,"target":1,"value":6, "label":"depicts"},
{"source":10,"target":1,"value":6, "label":"depicts"},
{"source":16,"target":1,"value":6, "label":"manageWebsite"},
{"source":16,"target":2,"value":5, "label":"manageWebsite"},
{"source":16,"target":3,"value":6, "label":"manageWebsite"},
{"source":16,"target":4,"value":6, "label":"manageWebsite"},
{"source":19,"target":18,"value":2, "label":"postedOn"},
{"source":18,"target":1,"value":6, "label":"childOf"},
{"source":17,"target":19,"value":8, "label":"describes"},
{"source":18,"target":11,"value":6, "label":"containsKeyword"},
{"source":17,"target":13,"value":3, "label":"containsKeyword"},
{"source":20,"target":13,"value":3, "label":"containsKeyword"},
{"source":20,"target":21,"value":3, "label":"postedOn"},
{"source":22,"target":20,"value":3, "label":"postedOn"},
{"source":23,"target":21,"value":3, "label":"manageWebsite"},
{"source":23,"target":24,"value":3, "label":"manageWebsite"},
{"source":23,"target":25,"value":3, "label":"manageWebsite"},
{"source":23,"target":26,"value":3, "label":"manageWebsite"}
]
}
var margin = {top: -5, right: -5, bottom: -5, left: -5};
var width = 500 - margin.left - margin.right,
height = 400- margin.top - margin.bottom;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-200)
.linkDistance(50)
.size([width + margin.left + margin.right, height + margin.top + margin.bottom]);
var zoom = d3.behavior.zoom()
.scaleExtent([1, 10])
.on("zoom", zoomed);
var drag = d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", dragstarted)
.on("drag", dragged)
.on("dragend", dragended);
var svg = d3.select("#map").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("id", "svg")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.right + ")")
.call(zoom);
var rect = svg.append("rect")
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all");
var container = svg.append("g");
//d3.json('http://blt909.free.fr/wd/map2.json', function(error, graph) {
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = container.append("g")
.attr("class", "links")
.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = container.append("g")
.attr("class", "nodes")
.selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.call(drag);
node.append("circle")
.attr("r", function(d) { return d.weight * 2+ 12; })
.style("fill", function(d) { return color(1/d.rating); });
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 + ")"; });
});
var linkedByIndex = {};
graph.links.forEach(function(d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
function isConnected(a, b) {
return linkedByIndex[a.index + "," + b.index] || linkedByIndex[b.index + "," + a.index];
}
node.on("mouseover", function(d){
node.classed("node-active", function(o) {
thisOpacity = isConnected(d, o) ? true : false;
this.setAttribute('fill-opacity', thisOpacity);
return thisOpacity;
});
link.classed("link-active", function(o) {
return o.source === d || o.target === d ? true : false;
});
d3.select(this).classed("node-active", true);
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", (d.weight * 2+ 12)*1.5);
})
.on("mouseout", function(d){
node.classed("node-active", false);
link.classed("link-active", false);
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", d.weight * 2+ 12);
});
function dottype(d) {
d.x = +d.x;
d.y = +d.y;
return d;
}
function zoomed() {
container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
d3.select(this).classed("dragging", true);
force.start();
}
function dragged(d) {
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}
function dragended(d) {
d3.select(this).classed("dragging", false);
}
$('#map')
.mousedown(function(){
$(this).css( 'cursor', 'move' );
})
.mouseup(function(){
$(this).css( 'cursor', 'auto' );
});
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.node-active{
stroke: #555;
stroke-width: 1.5px;
}
.link {
stroke: #555;
stroke-opacity: .3;
}
.link-active {
stroke-opacity: 1;
}
.overlay {
fill: none;
pointer-events: all;
}
#map{
border: 2px #555 dashed;
width:500px;
height:400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<body>
<div id="map"></div>
</body>
(sample SVG code borrowed from http://jsfiddle.net/JSDavi/qvco2Ljy/)
If anyone else comes up against this...this was my scenario:
If you have your Chrome inspector open, that is what causes this to fail, if you close the inspector for the page you're creating this effect on, it works perfectly.
You have:
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
d3.select(this).classed("dragging", true);
force.start();
}
That call to stopPropagation seems to prevent mouse down event. Unfortunately, changing it to preventDefault changes how drag&drop works (it moves whole graph around, instead of moving single nodes).
If it is only the cursor you need to change, why not use CSS for that? You already seem to change class of node to dragging, so you should be able to simply use following CSS:
.node.dragging {
cursor: move;
}
If you want cursor to change also when whole graph is dragged, you can add dragged class to the #map too:
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
$("#map").addClass("dragging");
d3.select(this).classed("dragging", true);
force.start();
}
// ...
function dragended(d) {
$("#map").removeClass("dragging");
d3.select(this).classed("dragging", false);
}
and then add CSS for that:
#map.dragging {
cursor: move;
}
var graph = {
"nodes":[
{"name":"1","rating":90,"id":2951},
{"name":"2","rating":80,"id":654654},
{"name":"3","rating":80,"id":6546544},
{"name":"4","rating":1,"id":68987978},
{"name":"5","rating":1,"id":9878933},
{"name":"6","rating":1,"id":6161},
{"name":"7","rating":1,"id":64654},
{"name":"8","rating":20,"id":354654},
{"name":"9","rating":50,"id":8494},
{"name":"10","rating":1,"id":6846874},
{"name":"11","rating":1,"id":5487},
{"name":"12","rating":80,"id":"parfum_kenzo"},
{"name":"13","rating":1,"id":65465465},
{"name":"14","rating":90,"id":"jungle_de_kenzo"},
{"name":"15","rating":20,"id":313514},
{"name":"16","rating":40,"id":36543614},
{"name":"17","rating":100,"id":"Yann_YA645"},
{"name":"18","rating":1,"id":97413},
{"name":"19","rating":1,"id":97414},
{"name":"20","rating":100,"id":976431231},
{"name":"21","rating":1,"id":9416},
{"name":"22","rating":1,"id":998949},
{"name":"23","rating":100,"id":984941},
{"name":"24","rating":100,"id":"99843"},
{"name":"25","rating":1,"id":94915},
{"name":"26","rating":1,"id":913134},
{"name":"27","rating":1,"id":9134371}
],
"links":[
{"source":6,"target":5,"value":6, "label":"publishedOn"},
{"source":8,"target":5,"value":6, "label":"publishedOn"},
{"source":7,"target":1,"value":4, "label":"containsKeyword"},
{"source":8,"target":10,"value":3, "label":"containsKeyword"},
{"source":7,"target":14,"value":4, "label":"publishedBy"},
{"source":8,"target":15,"value":6, "label":"publishedBy"},
{"source":9,"target":1,"value":6, "label":"depicts"},
{"source":10,"target":1,"value":6, "label":"depicts"},
{"source":16,"target":1,"value":6, "label":"manageWebsite"},
{"source":16,"target":2,"value":5, "label":"manageWebsite"},
{"source":16,"target":3,"value":6, "label":"manageWebsite"},
{"source":16,"target":4,"value":6, "label":"manageWebsite"},
{"source":19,"target":18,"value":2, "label":"postedOn"},
{"source":18,"target":1,"value":6, "label":"childOf"},
{"source":17,"target":19,"value":8, "label":"describes"},
{"source":18,"target":11,"value":6, "label":"containsKeyword"},
{"source":17,"target":13,"value":3, "label":"containsKeyword"},
{"source":20,"target":13,"value":3, "label":"containsKeyword"},
{"source":20,"target":21,"value":3, "label":"postedOn"},
{"source":22,"target":20,"value":3, "label":"postedOn"},
{"source":23,"target":21,"value":3, "label":"manageWebsite"},
{"source":23,"target":24,"value":3, "label":"manageWebsite"},
{"source":23,"target":25,"value":3, "label":"manageWebsite"},
{"source":23,"target":26,"value":3, "label":"manageWebsite"}
]
}
var margin = {top: -5, right: -5, bottom: -5, left: -5};
var width = 500 - margin.left - margin.right,
height = 400- margin.top - margin.bottom;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-200)
.linkDistance(50)
.size([width + margin.left + margin.right, height + margin.top + margin.bottom]);
var zoom = d3.behavior.zoom()
.scaleExtent([1, 10])
.on("zoom", zoomed);
var drag = d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", dragstarted)
.on("drag", dragged)
.on("dragend", dragended);
var svg = d3.select("#map").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("id", "svg")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.right + ")")
.call(zoom);
var rect = svg.append("rect")
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all");
var container = svg.append("g");
//d3.json('http://blt909.free.fr/wd/map2.json', function(error, graph) {
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = container.append("g")
.attr("class", "links")
.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = container.append("g")
.attr("class", "nodes")
.selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.call(drag);
node.append("circle")
.attr("r", function(d) { return d.weight * 2+ 12; })
.style("fill", function(d) { return color(1/d.rating); });
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 + ")"; });
});
var linkedByIndex = {};
graph.links.forEach(function(d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
function isConnected(a, b) {
return linkedByIndex[a.index + "," + b.index] || linkedByIndex[b.index + "," + a.index];
}
node.on("mouseover", function(d){
node.classed("node-active", function(o) {
thisOpacity = isConnected(d, o) ? true : false;
this.setAttribute('fill-opacity', thisOpacity);
return thisOpacity;
});
link.classed("link-active", function(o) {
return o.source === d || o.target === d ? true : false;
});
d3.select(this).classed("node-active", true);
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", (d.weight * 2+ 12)*1.5);
})
.on("mouseout", function(d){
node.classed("node-active", false);
link.classed("link-active", false);
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", d.weight * 2+ 12);
});
function dottype(d) {
d.x = +d.x;
d.y = +d.y;
return d;
}
function zoomed() {
container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
$("#map").addClass("dragging");
d3.select(this).classed("dragging", true);
force.start();
}
function dragged(d) {
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}
function dragended(d) {
$("#map").removeClass("dragging");
d3.select(this).classed("dragging", false);
}
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.node.dragging,
#map.dragging {
cursor: move;
}
.node-active{
stroke: #555;
stroke-width: 1.5px;
}
.link {
stroke: #555;
stroke-opacity: .3;
}
.link-active {
stroke-opacity: 1;
}
.overlay {
fill: none;
pointer-events: all;
}
#map{
border: 2px #555 dashed;
width:500px;
height:400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<body>
<div id="map"></div>
</body>

How to make nodes in sankey diagram clickable using d3.js library

Code Snippet :
We are using d3.js for this.
Sankey diagrams is made up of nodes and links.
Here the data comes from json file.
So how to make all the nodes clickable.
Which methods can we use with the rectangles so that we can make the nodes clickable.
<script>
var margin = {top: 1, right: 1, bottom: 6, left: 1},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var formatNumber = d3.format(",.0f"), //decimal places
format = function(d) { return formatNumber(d) + " TWh"; },
color = d3.scale.category20();
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var sankey = d3.sankey()
.nodeWidth(15)
.nodePadding(10)
.size([width, height]);
var path = sankey.link();
//d3.json("energy.json", function(energy) {
d3.json("numbers-subset.json", function(energy) {
sankey
.nodes(energy.nodes)
.links(energy.links)
.layout(32);
var link = svg.append("g").selectAll(".link")
.data(energy.links)
.enter().append("path")
.attr("class", "link")
.attr("d", path)
.style("stroke-width", function(d) { return Math.max(1, d.dy); })
.sort(function(a, b) { return b.dy - a.dy; });
link.append("title")
.text(function(d) { return d.source.name + " → " + d.target.name + "\n" + format(d.value); });
var node = svg.append("g").selectAll(".node")
.data(energy.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.call(d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", function() { this.parentNode.appendChild(this); })
.on("drag", dragmove));
node.append("rect")
.attr("height", function(d) { return d.dy; })
.attr("width", sankey.nodeWidth())
.style("fill", function(d) { return d.color = color(d.name.split("|")[0]); })
.style("stroke", function(d) { return d3.rgb(d.color).darker(2); })
.append("title")
.text(function(d) { return d.name + "\n" + format(d.value); });
node.append("text")
.attr("x", -6)
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr("transform", null)
.text(function(d) { return d.name; })
.filter(function(d) { return d.x < width / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
function dragmove(d) {
d3.select(this).attr("transform", "translate(" + d.x + "," + (d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))) + ")");
sankey.relayout();
link.attr("d", path);
}
});
</script>
D3.js is very powerful library give you control over each event to each pixel.
but we need to do one thing in the case of events.
Overlapping event we need to by forget .
Add following code in code.
var node = svg.append("g").selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"; })
.on("click",function(d){
if (d3.event.defaultPrevented) return;
alert("clicked!"+d.value);
})
.call(d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", function() {
this.parentNode.appendChild(this); })
.on("drag", dragmove));

d3.js: Drag is disabled when use zoom with force layout

I have seen this question: Is there a way to zoom into a D3 force layout graph?
But I got some unexpected behaivor from my graph - after few drags or zoom or pan all nodes just freezes and drag stop working.
I created this fiddle: http://jsfiddle.net/7gpweae9/9/
SO asked for code, so here is main part:
var svg = d3.select("#graph")
.append("svg:svg")
.attr("width", width)
.attr("height", height)
.attr("pointer-event", "all")
.append("svg:g")
.call(d3.behavior.zoom().on("zoom", zoom))
.append("svg:g");
svg.append("svg:rect")
.attr("width", width)
.attr("height", height)
.attr('fill', 'white');
var link = svg.selectAll(".link");
var node = svg.selectAll(".node");
var force = d3.layout.force()
.nodes(nodes)
.links(links)
.size([width,height])
.linkDistance(100)
.charge(-400)
.start();
var drag = d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", dragstarted)
.on("drag", dragged)
.on("dragend", dragended);
node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.call(drag);
node.append("circle")
.attr("class", "node-circle")
.attr("r", 12);
node.append("text")
.attr("x", 12)
.attr("y", ".35em")
.text(function(d) { return d.word; });
link = svg.selectAll(".link")
.data(links)
.enter().append("line")
.attr("class", "link");
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 + ")";
});
});
function zoom() {
svg.attr("transform",
"translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
d3.select(this).classed("dragging", true);
}
function dragged(d) {
d3.select(this).attr("x", d.x = d3.event.x).attr("y", d.y = d3.event.y);
}
function dragended(d) {
d3.select(this).classed("dragging", false);
}
Perhaps I missed something, I never used d3 before.
UPD: It seems that freezing occurs after a certain period of time.
I replaced d3.layout.force() to force.drag() and now it works almost fine.
var nodes;
var links;
prepareData();
var graph = document.querySelectorAll("#graph")[0];
var height = 500;
var width = 500;
var svg = d3.select("#graph").append("svg:svg")
.attr("width", width)
.attr("height", height)
.attr("pointer-event", "all")
.append("svg:g")
.call(d3.behavior.zoom().on("zoom", zoom))
.append("svg:g");
svg.append("svg:rect")
.attr("width", width)
.attr("height", height)
.attr('fill', 'white');
var link = svg.selectAll(".link");
var node = svg.selectAll(".node");
var force = d3.layout.force()
.nodes(nodes)
.links(links)
.size([width,height])
.linkDistance(100)
.charge(-400)
.start();
var drag = force.drag()
.origin(function(d) { return d; })
.on("dragstart", dragstarted)
.on("drag", dragged)
node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.call(drag);
node.append("circle")
.attr("class", "node-circle")
.attr("r", 12);
node.append("text")
.attr("x", 12)
.attr("y", ".35em")
.text(function(d) { return d.word; });
link = svg.selectAll(".link")
.data(links)
.enter().append("line")
.attr("class", "link");
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 + ")"; });
});
function zoom() {
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
}
function dragged(d) {
d3.select(this).attr("x", d.x = d3.event.x).attr("y", d.y = d3.event.y);
}
function prepareData() {
nodes = [{"index":0,"word":"edit"},{"index":1,"word":"course","sentences":[29859]},{"index":2,"word":"needs","sentences":[29859]},{"index":3,"word":"fit","sentences":[29859]},{"index":4,"word":"slides","sentences":[29859]},{"index":5,"word":"print","sentences":[29859]},{"index":6,"word":"can","sentences":[29859]}];
links = [{"source":0,"target":1},{"source":0,"target":2},{"source":0,"target":3},{"source":0,"target":4},{"source":0,"target":5},{"source":0,"target":6}]
}
svg {
border: 1px solid black;
}
.link {
stroke: #000;
stroke-width: 1px;
}
.node-circle {
cursor: move;
fill: #ccc;
stroke: #000;
stroke-width: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<body>
<div id="graph"></div>
</body>
You had to make your drag variable a function and change d3.behaviour.drag to force.drag :
function drag(){
return force.drag()
// .origin(function(d) { return d; })
.on("dragstart", dragstarted)
.on("drag", dragged)
.on("dragend", dragended);
}
Ive updated your fiddle
Working JSFIDDLE : http://jsfiddle.net/7gpweae9/15/

Categories