I got several nodes and links in place. Unfortunately those are "floating" out of the canvas. I am using D3.V4.js and found several guides how to solve the problem with D3.v3.js. Unfortuantely those doesn´t seem to work. Ideally a hidden or transparent frame would be arranged around the canvas area. I am new building D3 graphs, so I couldn´t figure it out yet.
Maybe you guys could help me to adjust the correct line in my code.
Thanks
var svg = d3.select("svg"),
width = window.innerWidth,
height = +svg.attr("height");
var color = d3.scaleOrdinal(d3.schemeCategory20);
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }).distance(100))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2))
.force("attraceForce",d3.forceManyBody().strength(-2));
var opacity = 0.25;
d3.json("datav2.json", function(error, graph) {
if (error) throw error;
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(graph.links)
.enter().append("line")
.style("stroke-width", 3)
.style("stroke-linecap", "round")
.attr("linkGroup",function(d) {return d.linkGroup; })
.attr("stroke-width", function(d) { return d.value; })
;
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", 15)
.attr("fill", "#ffffff")
.style("stroke-width", 2)
.style("stroke", function(d) { return color(d.group); })
.attr("nodeGroup",function(d) {return d.nodeGroup; })
.on("click", function(d) {
// This is to toggle visibility - need to do it on the nodes and links
d3.selectAll("line:not([linkGroup='"+d.nodeGroup+"'])")
.style("opacity", function() {
currentDisplay = d3.select(this).style("opacity");
currentDisplay = currentDisplay == "1" ? "0.1" : "1";
return currentDisplay;
});
d3.selectAll("circle:not([nodeGroup='"+d.nodeGroup+"'])")
.style("opacity",function() {
currentDisplay = d3.select(this).style("opacity");
currentDisplay = currentDisplay == "1" ? "0.1" : "1";
return currentDisplay;
});
d3.selectAll("text:not([nodeGroup='"+d.nodeGroup+"'])")
.style("opacity",function() {
currentDisplay = d3.select(this).style("opacity");
currentDisplay = currentDisplay == "1" ? "0.1" : "1";
return currentDisplay;
});
})
.on("mouseover", function(d) {
d3.select(this).style("cursor", "crosshair");
})
.on("mouseout", function(d) {
d3.select(this).style("cursor", "default");
})
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
// This is the label for each node
var text = svg.append("g").selectAll("text")
.data(graph.nodes)
.enter().append("text")
.attr("dy",-25)
.text(function(d) { return d.name;})
.attr("text-anchor", "middle")
.attr("nodeGroup",function(d) {return d.nodeGroup;} ) ;
node.append("title")
.text(function(d) { return d.name; });
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
function neighboring(a, b) {
return graph.links.some(function(d) {
return (d.source.id === a.source.id && d.target.id === b.target.id)
|| (d.source.id === b.source.id && d.target.id === a.target.id);
});
}
function ticked() {
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("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
//.attr("cx2", function(d) { return d.x = Math.max(d.width, Math.min(width - d.width, d.x)); })
//.attr("cy2", function(d) { return d.y = Math.max(d.height, Math.min(height - heightDelta - d.height, d.y)); });
text
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; });
}
});
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
Ok I found the issue and added a radius var with a size which fits to the nodes and modified the following line:
node
.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); })
.attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, d.y)); })
Related
I've a problem with my directed graph in d3js,in a few words:
if number of nodes < 24 the graph is rendered correctly
if number of nodes >= 24 everything was stacked on top left of svg but if I inspect my html code I see all nodes, links and labels...
this is my code:
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var simulation = d3.forceSimulation()
.force("x", d3.forceX().strength(8).x( function(d){ return yScale(d.type) }))
.force("y", d3.forceY().strength(10).y(height/2))
.force("center", d3.forceCenter().x(width / 2).y(height / 2)) // Attraction to the center of the svg area
.force("charge", d3.forceManyBody().strength(1)) // Nodes are attracted one each other of value is > 0
.force("collide", d3.forceCollide().strength(0.9).radius(50).iterations(10)) // Force that avoids circle overlapping
.force("link", d3.forceLink().distance(function(d){return d.link_distance}).strength(1))
var yScale = d3.scalePoint()
.domain([1, 2, 3])
.range([150, width-150])
.padding(0.6)
.round(false);
d3.json("{{=URL('professionista', 'get_current_plan_graph', extension=False)}}", function(error, graph) {
if (error) throw error;
var links = graph.links;
function getNeighbors(node) {
return links.reduce(function(neighbors, link) {
if (link.target.id === node.id) {
neighbors.push(link.source.id)
} else if (link.source.id === node.id) {
neighbors.push(link.target.id)
}
return neighbors
}, [node.id])
}
function isNeighborLink(node, link) {
return link.target.id === node.id || link.source.id === node.id
}
function getNodeColor(node, neighbors) {
if (Array.isArray(neighbors) && neighbors.indexOf(node.id) > -1) {
if (node.type === 1)
return "#3C99FB"
else if (node.type === 2)
return "#9EC2E2"
else if (node.type === 3)
return "#577EA7"
else
return '#dee2e6'
}
return '#dee2e6'
}
function getLinkColor(node, link) {
return isNeighborLink(node, link) ? '#000444' : '#E5E5E5'
}
function getTextColor(node, neighbors) {
return Array.isArray(neighbors) && neighbors.indexOf(node.id) > -1 ? 'green' : 'black'
}
function selectNode(selectedNode) {
var neighbors = getNeighbors(selectedNode)
nodeElement.attr('fill', function(node) {
return getNodeColor(node, neighbors)
})
labelElement.attr('fill', function(node) {
return getTextColor(node, neighbors)
})
linkElement.attr('stroke', function(link) {
return getLinkColor(selectedNode, link)
})
}
var linkElement = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(graph.links)
.enter().append("line")
.attr("stroke-width", 1)
.attr("stroke", "rgba(50, 50, 50, 0.2)");
var nodeElement = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter()
.append("circle")
.attr("r", 30)
.attr("fill", getNodeColor)
.on('click', selectNode)
var labelElement = svg.append("g")
.attr("class", "labels")
.selectAll("text")
.data(graph.nodes)
.enter().append("text")
.text(function(d) {
return d.codice;
})
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
function ticked() {
linkElement
.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; });
nodeElement
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
labelElement
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; });
}
});
what's wrong with this code?
This happen also if I disable all links and labels, the nodes goes to the corner, please help me!!!
I created a D3 visualization, but after the complete load, my visualisation isn't center :
I would like to have this result :
I use Angular 5 to execute my D3 visualization. My Data is loaded, it's work, but my visualization is on the left and not center. I would like to center my visualization. My code from my component :
export class BrainPageHomeComponent implements OnInit, AfterViewInit, OnDestroy {
public name: string;
public svg;
public color;
public simulation;
public link;
public node;
public miserables;
public tooltip;
constructor(
private brainService: BrainService,
) {
}
ngOnInit() {
}
ngAfterViewInit() {
this.loadBrain();
}
//Load Brain
public loadBrain() {
d3.select("svg").remove();
this.brainService.getBrain().subscribe(
data => {
this.miserables = data['data'];
this.svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.call(d3.zoom().on("zoom", function () {
let g = d3.select('svg > g');
g.attr("transform", d3.event.transform);
}))
.append("g");
let width = +this.svg.attr("width");
let height = +this.svg.attr("height");
this.color = d3.scaleOrdinal(d3.schemeCategory20);
this.simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function (d) {
return d.id;
}))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
this.render(this.miserables);
},
error => {
console.log(error);
});
}
ticked() {
this.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;
});
this.node
.attr("cx", function (d) {
return d.x;
})
.attr("cy", function (d) {
return d.y;
});
}
render(graph) {
let tooltip = d3.select("body")
.append("div")
.attr("class", "tooltip-message")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden");
this.link = this.svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(graph.links)
.enter().append("line")
.attr("stroke-width", function (d) {
return Math.sqrt(d.value);
});
this.node = this.svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", 5)
.attr("fill", (d) => {
return this.color(d.group);
})
//npm .on("click", function(d, i) { alert("Hello world"); })
.on("mouseover", function(node){
console.log(node);
tooltip.text(node.title);
return tooltip.style("visibility", "visible");
})
.on("mousemove", function(){return tooltip.style("top",
(d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");})
.call(d3.drag()
.on("start", (d) => {
return this.dragstarted(d)
})
.on("drag", (d) => {
return this.dragged(d)
})
.on("end", (d) => {
return this.dragended(d)
}));
this.node.append("title")
.text(function (d) {
return d.id;
});
this.simulation
.nodes(graph.nodes)
.on("tick", (nodes) => {
return this.ticked()
})
.stop();
this.simulation.force("link")
.links(graph.links);
this.simulation.restart();
}
dragstarted(d) {
if (!d3.event.active) this.simulation.alphaTarget(0.3).restart();
d.fx = d.x, d.fy = d.y;
}
dragged(d) {
d.fx = d3.event.x, d.fy = d3.event.y;
}
dragended(d) {
if (!d3.event.active) this.simulation.alphaTarget(0);
d.fx = null, d.fy = null;
}
ngOnDestroy() {
}
}
I tried many things :
Added viewBox attribute :
this.svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.call(d3.zoom().on("zoom", function () {
let g = d3.select('svg > g');
g.attr("transform", d3.event.transform);
}))
.attr("viewBox", "0 0 " + "100%" + " " + "100%" )
.attr("preserveAspectRatio", "xMidYMid meet");
.append("g");
Added restart simulation :
this.simulation.restart();
But my visualization is always on the left and not center.
I fixed my problem :
I replaced :
let width = +this.svg.attr("width");
let height = +this.svg.attr("height");
by :
let width = d3.select('svg').style("width");
let height = d3.select('svg').style("height");
width = width.substring(0, width.length - 2);
height = height.substring(0, height.length - 2);
Latest code attempt:
var node = svg.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", radius - .75)
.style("fill", function(d) { return fill(d.group); })
.style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); })
.call(force.drag);
var label = svg.selectAll("text")
.data(graph.nodes)
.enter()
.append("text")
.text(function(d){return d.id; });
.style("text-anchor", "middle")
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "red");
})
force
.nodes(graph.nodes)
.links(graph.links)
.on("tick", tick)
.start();
function tick() {
node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); })
.attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, 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; });
label.attr("x", function(d){ return d.x; })
.attr("y", function (d) {return d.y });
Hi Everyone,
I am a newbie to D3 and have spent almost two days on this problem so far to no avail!
I am trying to add node labels to a version of https://bl.ocks.org/mbostock/1129492
I've copy/pasted snippets of code from every forum response I can find and it either breaks my diagram (empty screen on execution) or has no effect (lots of pretty colored circles but no labels). I have been able to add labels to another force diagram successfully but that one was not bounded, and bounding is a key feature I'd like to have. At this stage I have not made any changes to the graph.json file Bostock put up. I am simply trying to get it to display the node text labels.
Can someone please tell me what code I need to write to get labels to show, and where and how to to insert it? I'm determined to not give up on this one!
Here's my code:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
circle {
stroke-width: 1.5px;
}
line {
stroke: #999;
}
text {
font: 12px "open sans";
fill: #fff;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var width = 960,
height = 500,
radius = 6;
var fill = d3.scaleOrdinal()
.range(["#a02a65","#2aa02a","#2aa0a0","#a0652a","#a02a2a","#2a2aa0","#65a02a","#a0a02a"])
var simulation = d3.forceSimulation()
.velocityDecay(0.1)
.force("x", d3.forceX(width / 2).strength(.05))
.force("y", d3.forceY(height / 2).strength(.05))
.force("charge", d3.forceManyBody().strength(-240))
.force("link", d3.forceLink().distance(50).strength(1));
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("https://[URL HERE]/graph.json", function(error, graph) {
if (error) throw error;
var link = svg.selectAll("line")
.data(graph.links)
.enter().append("line");
var node = svg.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", radius - .75)
.style("fill", function(d) { return fill(d.group); })
.style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
var labels = node.append("text")
.text(function(d) {
return d.id;
})
.attr('x', 6)
.attr('y', 3);
node.append("title")
.text(function(d) { return d.id; });simulation
.nodes(graph.nodes)
.on("tick", tick);
simulation.force('link')
.links(graph.links);
function tick() {
node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); })
.attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, 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 dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
</script>
I have modified the example from Mike Bostock to include labels for each node by doing the following:
The label for each node is in graph.nodes so first we create a
selection labels and perform a typical d3 data-join to add text
elements and set the label-text.
The positioning of the labels occurs in the tick() function. On
each step of the animation, we set the x and y attribute of the
text element according to the x and y value of the graph.node
element.
Please note that this example uses d3 v3 so there will be some changes to the syntax - primarily the names used for scale etc. More details can be found here.
I have not attempted to position the text to avoid overlapping. This is reasonably involved and discussed elsewhere like this other SO post.
var width = 960,
height = 500,
radius = 6;
var fill = d3.scale.category20();
var force = d3.layout.force()
.gravity(.05)
.charge(-240)
.linkDistance(50)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("https://gist.githubusercontent.com/mbostock/1129492/raw/9513c3fe193673a09e161d49d00a587fd806bdf5/graph.json", function(error, graph) {
if (error) throw error;
var link = svg.selectAll("line")
.data(graph.links)
.enter().append("line");
var node = svg.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", radius - .75)
.style("fill", function(d) { return fill(d.group); })
.style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); })
.call(force.drag);
var labels = svg.selectAll("text")
.data(graph.nodes)
.enter().append('text')
.text(function (d){return d.name});
force
.nodes(graph.nodes)
.links(graph.links)
.on("tick", tick)
.start();
function tick() {
node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); })
.attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, 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; });
labels.attr('x', function(d) { return d.x; })
.attr('y', function(d) { return d.y; });
}
});
circle {
stroke-width: 1.5px;
}
line {
stroke: #999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
I am trying to give different shape or image icons for different nodes.
Like, for Target node i.e dark blue you can see in the js fiddle I want to give as a rectangle to an image icon and for a lighter circle with different shape or image icon.I have followed this Link also but cant able to make it work.
Here is the js fiddle like:
https://jsfiddle.net/AmitSah/bp6p3p92/
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
radius = 10;
/*svg.call(d3.zoom().on("zoom", function () {
svg.attr("transform", d3.event.transform);
}));*/
var color = d3.scaleOrdinal(d3.schemeCategory20);
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.node_id; }).strength(1) )
//.force("charge", d3.forceManyBody())
.force("collide", d3.forceCollide(radius + 1).iterations(4))
.force("center", d3.forceCenter(width / 2, height / 2));
// projection definition
var projection = d3.geoAlbers()
.scale(1280)
.translate([width / 2, height / 2]);
// path generator definition for major cities, including point radius
var path = d3.geoPath()
.projection(projection)
.pointRadius(2);
// draws the states
d3.json("https://raw.githubusercontent.com/LogicalInsightscg/Web-Mobile-Dashboard/master/us_new.json", function(error, us_new) {
if (error) return console.error(error);
svg.selectAll(".states")
.data(topojson.feature(us_new, us_new.objects.states).features)
.enter().append("path")
.attr("class", function(d) { return "states " + d.id; })
.attr("d", path);
// adding state boundaries
svg.append("path")
.datum(topojson.mesh(us_new, us_new.objects.states))
.attr("d", path)
.attr("class", "state-boundary");
d3.json("https://raw.githubusercontent.com/LogicalInsightscg/Web-Mobile-Dashboard/master/nodesandlinks.json", function(error, graph) {
if (error) throw error;
// build the arrow.
svg.append("svg:defs").selectAll("marker")
.data(["end"]) // Different link/path types can be defined here
.enter().append("svg:marker") // This section adds in the arrows
.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:line")
.attr("d", "M0,-5L10,0L0,5");
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(graph.links)
.enter().append("line")
.attr("stroke-width", function(d) { return Math.sqrt(d.referrals); })
.attr("marker-end", "url(#end)");
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", 5)
.attr("fill", function(d) { return color(d.group); })
//.attr("fixed", true)
.attr("cx", function(d) {
return projection([d.longitude, d.latitude])[0];
})
.attr("cy", function(d) {
return projection([d.longitude, d.latitude])[1];
})
/* .call(d3.drag()
.on("end", dragended)); */
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
node.attr('fx', function(d) { return projection([d.longitude, d.latitude])[0]; })
.attr('fy', function(d) { return projection([d.longitude, d.latitude])[1]; });
link.attr('x1', function(d) { return projection([d.source.longitude, d.source.latitude])[0]; })
.attr('y1', function(d) { return projection([d.source.longitude, d.source.latitude])[1]; })
.attr('x2', function(d) { return projection([d.target.longitude, d.target.latitude])[0]; })
.attr('y2', function(d) { return projection([d.target.longitude, d.target.latitude])[1]; });
node.append("title")
.text(function(d) { return d.node_name; });
function ticked() {
link
.attr("distance", 10)
// .attr("x1", function(d) { return d.source.x; })
// .attr("y1", function(d) { return d.source.y; })
.attr('x1', function(d) { return projection([d.source.longitude, d.source.latitude])[0]; })
.attr('y1', function(d) { return projection([d.source.longitude, d.source.latitude])[1]; })
.attr('x2', function(d) { return projection([d.target.longitude, d.target.latitude])[0]; })
.attr('y2', function(d) { return projection([d.target.longitude, d.target.latitude])[1]; });
node.attr('cx', function(d) {if (d.group > 0) { return projection([d.longitude, d.latitude])[0]; }
else { return d.x; }})
.attr('cy', function(d) {if (d.group > 0) { return projection([d.longitude, d.latitude])[1]; }
else { return d.y; }});
}
/* function ticked() {
link.attr('x1', function(d) { return projection([d.source.longitude, d.source.latitude])[0]; })
.attr('y1', function(d) { return projection([d.source.longitude, d.source.latitude])[1]; })
.attr('x2', function(d) { return projection([d.target.longitude, d.target.latitude])[0]; })
.attr('y2', function(d) { return projection([d.target.longitude, d.target.latitude])[1]; });
node.attr('r', width/100)
.attr('cx', function(d) { return projection([d.longitude, d.latitude])[0]; })
.attr('cy', function(d) { return projection([d.longitude, d.latitude])[1]; });
} */
});
});
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
Can anyone help me to do this?
EDITED:
Kindly see this image:
Network Map
d3.selectAll(".company").append("rect")
.attr("width", 20)
.attr("height", 20)
.data(someData)
.attr("x", function(d) {
if (d.cat == 2)
{
return projection([d.longitude, d.latitude])[0];
}
})
.attr("y", function(d) {
if (d.cat == 2)
{
return projection([d.longitude, d.latitude])[1];
}
});
Thanks,
Amit Sah
The easiest way would be to have something in the data that you can use to set the attributes, i.e.
.attr('stroke-color', function(){
if
(d.dataAtt = someAttribute, return black)
else if
(d.dataAtt = otherAttribute, return white)
Or if you want to set the target nodes to a different colour, you could use d3.select to select all the node id's in the target link array, then change the attributes of only those nodes. Setting the node id might help select the correct nodes (see the bottom line):
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", 5)
.attr("id", d.graph.nodes.id)//or something
Edit:
var node = svg.append("g")
.attr("class", function(){
if
(d.dataAtt = someAttribute, return Aclass)
else if
(d.dataAtt = otherAttribute, return Bclass))//it would be easiest to separate the nodes by class
.data(graph.nodes)
.enter()
.attr("id", d.graph.nodes.id)//or something
d3.selectAll(".Aclass")
.append("rect")
d3.selectAll(".Bclass")
.append("circle")
You could use the source/target array to select the nodes where there id is in one or the other, but without seeing your data, I don't know if that would be appropriate.
I am making a timeline sort of project. As of right now, my code looks like the following:
var width = 960,
height = 500;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-300)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("input.json", function(error, graph) {
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); })
.style("visibility", function(d) {
return d.value == 2 ? "hidden" : "visible";
});
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 20)
.style("fill", function(d) { return color(d.group); })
.call(force.drag)
.style("visibility", function(d) {
return d.group == 1 ? "hidden" : "visible";
})
.on("mouseover", function(d) {
if(d.group == 2) {
node.filter(function(d) { return d.group == 1; }).style("visibility", "visible");
link.filter(function(d) { return d.value == 2; }).style("visibility", "visible");
texts.filter(function(d) { return d.value == 2; }).style("visibility", "visible");
}
}).on("mouseout", function(d) {
if(d.group == 2) {
node.filter(function(d) { return d.group == 1; }).style("visibility", "hidden");
link.filter(function(d) { return d.value == 2; }).style("visibility", "hidden");
}
});
var texts = svg.selectAll("text.label")
.data(graph.nodes)
.enter().append("text")
.attr("class", "label")
.attr("fill", "black")
.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("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
texts.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
});
});
As of right now, the text, or labelsconstantly show, even when the nodes and links don't. I'm wondering what I need to do? I don't know if I can assign a value or group to the labels