Fit the d3js graph in a simple html page - javascript

I am trying to use the example from here, and my files are as follows:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<meta charset="utf-8">
<style>
.node circle {
fill: #999;
}
.node text {
font: 10px sans-serif;
}
.node--internal circle {
fill: #555;
}
.node--internal text {
text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff;
}
.link {
fill: none;
stroke: #555;
stroke-opacity: 0.4;
stroke-width: 1.5px;
}
html, body {
height: 100%;
}
html {
display: table;
margin: auto;
}
body {
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<svg width="960" height="2000"></svg>
<script src="d3.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g").attr("transform", "translate(40,0)");
var tree = d3.cluster()
.size([height, width - 160]);
var stratify = d3.stratify()
.parentId(function(d) { return d.id.substring(0, d.id.lastIndexOf(".")); });
d3.csv("test.csv", function(error, data) {
if (error) throw error;
var root = stratify(data)
.sort(function(a, b) { return (a.height - b.height) || a.id.localeCompare(b.id); });
tree(root);
var link = g.selectAll(".link")
.data(root.descendants().slice(1))
.enter().append("path")
.attr("class", "link")
.attr("d", function(d) {
return "M" + d.y + "," + d.x
+ "C" + (d.parent.y + 100) + "," + d.x
+ " " + (d.parent.y + 100) + "," + d.parent.x
+ " " + d.parent.y + "," + d.parent.x;
});
var node = g.selectAll(".node")
.data(root.descendants())
.enter().append("g")
.attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
node.append("circle")
.attr("r", 2.5);
node.append("text")
.attr("dy", 3)
.attr("x", function(d) { return d.children ? -8 : 8; })
.style("text-anchor", function(d) { return d.children ? "end" : "start"; })
.text(function(d) { return d.id.substring(d.id.lastIndexOf(".") + 1); });
});
</script>
</body>
</html>
and test.csv
id
country
country.USA
country.Canada
country.Russia
country.China
country.India
country.England
country.USA.Wisconsin
country.USA.Wisconsin.Madison
country.USA.Washington DC
country.Canada.Toronto
country.Canada.Ottawa
country.Russia.St Petersburg
country.India.Karnataka
country.India.Maharashtra
country.India.Delhi
country.India.Karnataka.Bangalore
country.India.Karnataka.Bangalore.city
country.India.Karnataka.Bangalore.rural
country.India.Karnataka.Mysore
country.India.Karnataka.Mangalore
country.India.Maharashtra.Mumbai
country.India.Maharashtra.Pune
The resulting output is cutting off the first node, i.e. instead of country, it is displaying just ountry as highlighted in the screenshot below:
How to resolve this? This is just a sample, I have actual csv with the name of the nodes of length 10 Characters. How to auto-adjust the final output.

Your line with the g defined in it, you probably just want to increase the x translation.
g = svg.append("g").attr("transform", "translate(40,0)");
becomes
g = svg.append("g").attr("transform", "translate(60,0)");
This moves the group which contains the entire visualization over some additional pixels. If you want to get clever about it you could actually measure the length of the string "country" and translate by that amount. For example:
const countryText = g.append("g")
.attr("class", "node") //apply all the same classes to ensure css rules match
.append("text")
.text("country");
const width = countryText.node().getComputedTextLength()
g.attr("transform", `translate(${width}, 0)`);
Server Side: A word of warning about measuring strings though. This is only supported in an environment with a browser, which can make server side rendering (or automated tests that use something like Node) very difficult to work with.

If you look at Bostock's code, you can see that he's appending everything to a group, which is being translated 40 pixels to the right:
g = svg.append("g").attr("transform", "translate(40,0)");
Solution: translate more than that:
g = svg.append("g").attr("transform", "translate(50,0)");
Here is your updated bl.ocks: https://bl.ocks.org/anonymous/c873ba1afc1d58a1ea5a13a093468d39

Related

jquery dialog box appended to d3 js tree on drag and drop

I have a tree that is created in d3 and each node can be dragged and dropped in any point.
I want my code to pop up a dialog box with several choices when I drop a node on specific location.
I do not have any idea how it can be implemented in d3. I searched and found out that this can be done with jquery but I do not know how I can apply jquery into a d3 environment.
An example similar to my problem is explained in here . I implemented something similar to this but my code does not show any jquery code in my webpage.
So my first question is that how can I use d3 and jquery at the same time? A simple example can help me. (like clicking on a node of a tree in d3 svg and a popup of a dialog box in jquery)
And my second question is related to my code snippet. I have provided my code below, if anyone can help me with the implementation of a popup dialog box in the commented area I would really appreciate that.
var treeData =
{
"name": "A",
"children": [
{
"name": "B",
"children": [
{ "name": "C" },
{ "name": "D" }
]
},
{
"name": "E"
}
]
};
var margin = {top: 40, right: 90, bottom: 50, left: 90},
width = 800 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// declares a tree layout and assigns the size
var treemap = d3.tree()
.size([width, height]);
// assigns the data to a hierarchy using parent-child relationships
var nodes = d3.hierarchy(treeData);
// maps the node data to the tree layout
nodes = treemap(nodes);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom),
g = svg.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// adds the links between the nodes
var link = g.selectAll(".link")
.data( nodes.descendants().slice(1))
.enter().append("path")
.attr("class", "link")
.attr("d", function(d) {
return "M" + d.x + "," + d.y
+ "C" + d.x + "," + (d.y + d.parent.y) / 2
+ " " + d.parent.x + "," + (d.y + d.parent.y) / 2
+ " " + d.parent.x + "," + d.parent.y;
});
// adds each node as a group
var node = g.selectAll(".node")
.data(nodes.descendants())
.enter().append("g")
.attr("class", function(d) {
return "node" +
(d.children ? " node--internal" : " node--leaf"); })
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"; })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
// adds the circle to the node
node.append("circle")
.attr('r', 10).attr("id", "nodeid");
node.append("text")
.attr("dy", ".60em")
.attr("y", function(d) { return d.children ? -20 : 20; })
.style("text-anchor", "middle")
.text(function(d) { return d.data.name; });
function dragstarted(d) {
d3.select(this).raise().classed("active", true);
dragStarted = null;
}
function dragged(d) {
d.x += d3.event.dx
d.y += d3.event.dy
d3.select(this).attr("transform", "translate(" + d.x + "," + d.y + ")");
}
function dragended(d) {
draggedNode=d;
if (draggedNode.parent==d.parent){
//A popup dialog box should come here
console.log("a dialogbox in here")
//my implemented yet not working jquery dialog box
$( document ).ready(function() {
$("#nodeid").click(function (e) {
$("#modal01").show();
$("#box").show();
})
})
}
d3.select(this).classed("active", false);
}
.node circle {
fill: black;
stroke: steelblue;
stroke-width: 1px;
}
.node text { font: 12px sans-serif; }
.node--internal text {
text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1px;
}
.modal {
position: absolute;
display: none;
z-index: 10;
}
.modal-box {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 5;
display: none
}
<!DOCTYPE html>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<body>
<!-- load the d3.js library -->
<script src="mytree.js"></script>
<div id="modal01" class="modal">Blabla</div>
<div id="box" class="modal-box"></div>
</body>
Just comment the lines that are not needed.
How to close the dialog is still todo.
function dragended(d) {
draggedNode=d;
if (draggedNode.parent==d.parent){
//A popup dialog box should come here
console.log("a dialogbox in here")
//my implemented yet not working jquery dialog box
// $( document ).ready(function() {
// $("#nodeid").click(function (e) {
$("#modal01").show();
$("#box").show();
// })
// })
}
d3.select(this).classed("active", false);
}
I finally found the answer to my question. It basically did not load styles from jquer and the styles of the given modal and box is not completely correct. I am posting my answer in here so if anybody face with the same problem can see it.
Just add these lines to your head tag in html first:
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
Then you can Add your dialog box to the body of your html code:
<div id = "dialog-1"
title = "Dialog Title goes here...">This my first jQuery UI Dialog!
<button id = "opener">Open Dialog</button>
</div>
And last we should add the jquery codes to our javascript code:
$( "#dialog-1" ).dialog( "open" );

Ordinal brushing in parallel coordinates in d3 V4?

I am looking for parallel coordinate visualization in d3.js that has both ordinal and numerical values in d3 V4. I have created a sample http://plnkr.co/edit/TiM6ZsvMTTBhh8ZdMoFQ?p=preview
I am trying to brush the 'name' column as well. It seems there are lots of changes in d3 brush in V4. Also is there a way where I can snap the brushing area in both cases of ordinal and numerical columns.
Any help would be highly appreciated.
Thanks
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
font: 10px sans-serif;
}
.background path {
fill: none;
stroke: #ddd;
stroke-opacity: .4;
shape-rendering: crispEdges;
}
.foreground path {
fill: none;
stroke: steelblue;
stroke-opacity: .7;
}
.brush .extent {
fill-opacity: .3;
stroke: #fff;
shape-rendering: crispEdges;
}
.axis line,
.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.axis text {
text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
cursor: move;
}
</style>
<body>
<script src="http://d3js.org/d3.v4.min.js"></script>
<script>
var margin = {top: 30, right: 10, bottom: 10, left: 10},
width = 600 - margin.left - margin.right,
height = 200 - margin.top - margin.bottom;
var x = d3.scaleBand().rangeRound([0, width]).padding(1),
y = {},
dragging = {};
var line = d3.line(),
//axis = d3.axisLeft(x),
background,
foreground,
extents;
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.top + ")");
var quant_p = function(v){return (parseFloat(v) == v) || (v == "")};
d3.csv("cars.csv", function(error, cars) {
// Extract the list of dimensions and create a scale for each.
//cars[0] contains the header elements, then for all elements in the header
//different than "name" it creates and y axis in a dictionary by variable name
console.log("ok");
dimensions = d3.keys(cars[0]);
x.domain(dimensions);
dimensions.forEach(function(d) {
var vals = cars.map(function(p) {return p[d];});
if (vals.every(quant_p)){
y[d] = d3.scaleLinear()
.domain(d3.extent(cars, function(p) {
return +p[d]; }))
.range([height, 0])
}
else{
y[d] = d3.scalePoint()
.domain(vals.filter(function(v, i) {return vals.indexOf(v) == i;}))
.range([height, 0],1);}
})
extents = dimensions.map(function(p) { return [0,0]; });
// Add grey background lines for context.
background = svg.append("g")
.attr("class", "background")
.selectAll("path")
.data(cars)
.enter().append("path")
.attr("d", path);
// Add blue foreground lines for focus.
foreground = svg.append("g")
.attr("class", "foreground")
.selectAll("path")
.data(cars)
.enter().append("path")
.attr("d", path);
// Add a group element for each dimension.
var g = svg.selectAll(".dimension")
.data(dimensions)
.enter().append("g")
.attr("class", "dimension")
.attr("transform", function(d) { return "translate(" + x(d) + ")"; })
.call(d3.drag()
.subject(function(d) { return {x: x(d)}; })
.on("start", function(d) {
dragging[d] = x(d);
background.attr("visibility", "hidden");
})
.on("drag", function(d) {
dragging[d] = Math.min(width, Math.max(0, d3.event.x));
foreground.attr("d", path);
dimensions.sort(function(a, b) { return position(a) - position(b); });
x.domain(dimensions);
g.attr("transform", function(d) { return "translate(" + position(d) + ")"; })
})
.on("end", function(d) {
delete dragging[d];
transition(d3.select(this)).attr("transform", "translate(" + x(d) + ")");
transition(foreground).attr("d", path);
background
.attr("d", path)
.transition()
.delay(500)
.duration(0)
.attr("visibility", null);
}));
// Add an axis and title.
g.append("g")
.attr("class", "axis")
.each(function(d) { d3.select(this).call(d3.axisLeft(y[d]));})
//text does not show up because previous line breaks somehow
.append("text")
.attr("fill", "black")
.style("text-anchor", "middle")
.attr("y", -9)
.text(function(d) { return d; });
// Add and store a brush for each axis.
g.append("g")
.attr("class", "brush")
.each(function(d) {
d3.select(this).call(y[d].brush = d3.brushY().extent([[-8, 0], [8,height]]).on("brush start", brushstart).on("brush", brush_parallel_chart));
})
.selectAll("rect")
.attr("x", -8)
.attr("width", 16);
});
function position(d) {
var v = dragging[d];
return v == null ? x(d) : v;
}
function transition(g) {
return g.transition().duration(500);
}
// Returns the path for a given data point.
function path(d) {
return line(dimensions.map(function(p) { return [position(p), y[p](d[p])]; }));
}
function brushstart() {
d3.event.sourceEvent.stopPropagation();
}
// Handles a brush event, toggling the display of foreground lines.
function brush_parallel_chart() {
for(var i=0;i<dimensions.length;++i){
if(d3.event.target==y[dimensions[i]].brush) {
extents[i]=d3.event.selection.map(y[dimensions[i]].invert,y[dimensions[i]]);
}
}
foreground.style("display", function(d) {
return dimensions.every(function(p, i) {
if(extents[i][0]==0 && extents[i][0]==0) {
return true;
}
return extents[i][1] <= d[p] && d[p] <= extents[i][0];
}) ? null : "none";
});
}
</script>

If then else HTML/CSV file

I am currently building an organisation chart for my company using an html code (pasted below) build by the genius Mr Bostock. The code is calling a .csv file (flare.csv) where I am organizing my data (3 different columns: Employee Name/Employee span of control (5 ranges)/Employee Salary (6 ranges)).
I want to know if it is possible to change the color of the dots/circles on the diagram depending on the two parameters Span of control and Salary (Ranges).
Maybe a diagram for Span of control and another one for Salary.
Let s say if the Span of control of that employee is between 1 and 3 (Flare.csv file) then his circle on the chart will be yellow.
Thank you in advance for your answers.
Cheers,
Alex
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node circle {
fill: #999;
}
.node text {
font: 12px sans-serif;
}
.node--internal circle {
fill: #555;
}
.node--internal text {
text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff;
}
.link {
fill: none;
stroke: #555;
stroke-opacity: 0.4;
stroke-width: 1.5px;
}
</style>
<svg width="960" height="900"></svg>
<script src="d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + (height / 2 + 20) + ")");
var stratify = d3.stratify()
.parentId(function(d) { return d.id.substring(0, d.id.lastIndexOf(".")); });
var cluster = d3.cluster()
.size([360, width / 2 - 120]);
d3.csv("flare.csv", function(error, data) {
if (error) throw error;
var root = stratify(data)
.sort(function(a, b) { return a.height - b.height || a.id.localeCompare(b.id); });
cluster(root);
var link = g.selectAll(".link")
.data(root.descendants().slice(1))
.enter().append("path")
.attr("class", "link")
.attr("d", function(d) {
return "M" + project(d.x, d.y)
+ "C" + project(d.x, (d.y + d.parent.y) / 2)
+ " " + project(d.parent.x, (d.y + d.parent.y) / 2)
+ " " + project(d.parent.x, d.parent.y);
});
var node = g.selectAll(".node")
.data(root.descendants())
.enter().append("g")
.attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
.attr("transform", function(d) { return "translate(" + project(d.x, d.y) + ")"; });
node.append("circle")
.attr("r", 2.5);
node.append("text")
.attr("dy", "0.31em")
.attr("x", function(d) { return d.x < 180 === !d.children ? 6 : -6; })
.style("text-anchor", function(d) { return d.x < 180 === !d.children ? "start" : "end"; })
.attr("transform", function(d) { return "rotate(" + (d.x < 180 ? d.x - 90 : d.x + 90) + ")"; })
.text(function(d) { return d.id.substring(d.id.lastIndexOf(".") + 1); });
});
function project(x, y) {
var angle = (x - 90) / 180 * Math.PI, radius = y;
return [radius * Math.cos(angle), radius * Math.sin(angle)];
}
</script>

Can't get d3 donut chart labels to line up correctly

I am having trouble getting a two-ring donut chart's labels to line up correctly. I think it has something to do with appending the labels to the gs var instead of the path var but if I make that switch, the labels are not visible at all. In the end, I would like each label to be centered on the angle and radius of each slice.
Code is here:
<html>
<body>
<meta charset="utf-8">
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: auto;
position: relative;
width: 960px;
}
text {
font: 10px sans-serif;
}
form {
position: absolute;
right: 10px;
top: 10px;
}
</style>
<svg class="chart"></svg>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var dataset = {
bip: [.2, .1, .3, .05, .05, .2],
position: [0, 25, 35, 25, 15, 0]
};
var width = 450,
height = 450,
cwidth = 250;
var color = d3.scale.category10();
var pie = d3.layout.pie()
.sort(null)
.startAngle(Math.PI * -.25)
.endAngle(Math.PI * .25)
;
var arc = d3.svg.arc();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.style("border", "1px solid black")
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height + ")")
;
var gs = svg.selectAll("g")
.data(d3.values(dataset))
.enter()
.append("g");
var path = gs.selectAll("path")
.data(function(d) { return pie(d); })
.enter()
.append("path")
.attr("fill", function(d,i,j) {
return "rgb(" + 255*(1-j) + "," + (166 + d3.round(89*d.value,0))*(1-j) + "," + d3.round(255*d.value,0)*(1-j) + ")" ;
})
.attr("d", function(d, i, j) {
return arc.innerRadius(cwidth*j).outerRadius(cwidth-5+50*j) (d);
})
.style('stroke', 'white')
.style('stroke-width', 5)
;
//Labels
gs.append("svg:text")
.attr("transform", function(d, i, j) {
d.startAngle = (Math.PI * -.75 + Math.PI*i/6);
d.endAngle = (Math.PI * .25 + Math.PI*i/6);
d.innerRadius = cwidth*j;
d.outerRadius = cwidth-5+50*j;
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.style("fill", "white")
.style("font", "bold 12px Arial")
.text(function(d, i, j) { return d; });
</script>
</body>
</html>
Example is here:
http://jsfiddle.net/sgrossman/kzh7c8mn/
Appreciate the help.
I think that you are right about the problem being attaching to the gs vs. the path var.
I have a fiddle here that is working a bit like you want. It creates text and textPaths per arc element and links them via an ID. Centering is not perfect but could be tuned through trial and error.
//Add an id to the path
.attr("id", function(d, i, j){return 'path_' + i + '_'+ j;})
Add a svg:text and textPath per data point:
gs.selectAll("g").data(function (d, i, j) {
return d;
})
.enter().append('svg:text')
.attr("dx", function(d,i,j){
if(j==1) {return (d * 2) + 8;}
else {return (d * 250) - 15;}
})
.attr("dy", 25)
.append('textPath')
.attr("stroke","white")
//Link via xlink:href
.attr("xlink:href",function(d,i,j){
return '#path_' + i + '_' + j;
})
.text(function (d, i, j) {
return d;
});
JSFiddle

How to make a node of a D3 force directed graph stay at the place after we drag it there

i have a force directed graph where i can show some relationship among some numbers.And we can drag the nodes after releasing the nodes the nodes will come back to the original position.but here i want that i will drag the nodes. Upto here i am able drag all the nodes to some position and the are not coming back to the original position,but i want also the links with them ...
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.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;
cursor: pointer;
}
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;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var links = [];
var nodes = {};
// Compute the distinct nodes from the links.
var width = 960, height = 500;
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");
d3.json(
"test.json",
function(error, directed) {
links=directed.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 force = d3.layout.force().nodes(
d3.values(nodes)).links(links).size(
[ width, height ]).linkDistance(60).charge(
-300).on("tick", tick).start();
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(d3.behavior.drag().origin(function(d) {
return d;
}).on("drag", function(d) {
d.x = d3.event.x, d.y = d3.event.y;
d3.select(this).attr("cx", d.x).attr("cy", d.y);
link.filter(function(l) {
return l.source === d;
}).attr("x1", d.x).attr("y1", d.y);
link.filter(function(l) {
return l.target === d;
}).attr("x2", d.x).attr("y2", d.y);
}));
circle.append("title").text(function(d){
return d.name;
});
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;
});
//selection is happening
var selected = circle.filter(function(d) {
return d.name;
});
selected.each(function(d) {
// d contains the data for the node and this is the circle element
console.log(d.name);
});
var drag = d3.behavior.drag()
.on("drag", function(d,i) {
d.x += d3.event.dx
d.y += d3.event.dy
d3.select(this).attr("transform", function(d,i){
return "translate(" + d.x + "," + d.y + ")";
})
});
var circle = svg.append("g").selectAll("circle")
.data(force.nodes()).enter().append(
"circle").attr("r", 6).on("click",
clickfn).call(drag);
var clickfn = function(circle) {
alert();
}
// 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 + ")";
}
});
</script>
this is the test.json
{"links":[{"source":"9804500485","target":"9804086391","type":"licensing"},{"source":"9804500485","target":"8420697490","type":"resolved"},{"source":"9804086391","target":"9804056963","type":"licensing"},{"source":"8420697490","target":"9804086391","type":"suit"},{"source":"9804086391","target":"9874525986","type":"licensing"},{"source":"9804500485","target":"9806895472","type":"resolved"},{"source":"8420697490","target":"9836444045","type":"licensing"},{"source":"9836444045","target":"9804500485","type":"licensing"},{"source":"9804500485","target":"9874525986","type":"licensing"},{"source":"9836444045","target":"9804086391","type":"suit"}]}

Categories