Currently, I am building a system, and I am having some trouble with the update function.
Essentially, I am trying to add new nodes to a D3 tree. A new child node can be added when the user clicks the "add button" of a node. Each add button can be found on the left side of each node.
I have followed Mike Bostock's general update pattern. Once I click on the button, the only "new" data element should be the newly created child node, but it looks like the entire data is being treat as "new". I came to this conclusion when I looked at the class names for each node and the obvious fact that there is a transition of all the nodes coming to the central node and disappearing. The other original data should be "updated", but it's not. Can anyone please gently point out as to why this is happening?
A working sample of my code can be found in this jfiddle link.
EDIT 06/09
Given Gordon's suggestion, I have found a unique field for both of my nodes and link. So to uniquely identify the data I have made the following change:
NODE
.data(d, d => d.data.name)
LINK
.data(d, d => d.source.data.name)
This change works (mostly), but I see that some weird behaviors are still occurring: (1) Branch 7.2.1 is still being recognized a new node and disappear; (2) links are not being properly aligned with their respective node after the second "add" or so. I think my two small edits are affecting this because when I went back to the original code, the lines are being properly drawn, despite the fact they're transitioning away. Thoughts? Advice?
HTML
<div id="div-mindMap">
CSS
.linkMindMap {
fill: none;
stroke: #555;
stroke-opacity: 0.4;
}
rect {
fill: white;
stroke: #3182bd;
stroke-width: 1.5px;
}
JS
const widthMindMap = 700;
const heightMindMap = 700;
let parsedData;
let parsedList = {
"name": " Stapler",
"children": [{
"name": " Bind",
"children": []
},
{
"name": " Nail",
"children": []
},
{
"name": " String",
"children": []
},
{
"name": " Glue",
"children": [{
"name": "Gum",
"children": []
},
{
"name": "Sticky Gum",
"children": []
}
]
},
{
"name": " Branch 3",
"children": []
},
{
"name": " Branch 4",
"children": [{
"name": " Branch 4.1",
"children": []
},
{
"name": " Branch 4.2",
"children": []
},
{
"name": " Branch 4.1",
"children": []
}
]
},
{
"name": " Branch 5",
"children": []
},
{
"name": " Branch 6",
"children": []
},
{
"name": " Branch 7",
"children": []
},
{
"name": " Branch 7.1",
"children": []
},
{
"name": " Branch 7.2",
"children": [{
"name": " Branch 7.2.1",
"children": []
},
{
"name": " Branch 7.2.1",
"children": []
}
]
}
]
}
let svgMindMap = d3.select('#div-mindMap')
.append("svg")
.attr("id", "svg-mindMap")
.attr("width", widthMindMap)
.attr("height", heightMindMap);
let backgroundLayer = svgMindMap.append('g')
.attr("width", widthMindMap)
.attr("height", heightMindMap)
.attr("class", "background")
let gLeft = backgroundLayer.append("g")
.attr("transform", "translate(" + widthMindMap / 2 + ",0)")
.attr("class", "g-left");
let gLeftLink = gLeft.append('g')
.attr('class', 'g-left-link');
let gLeftNode = gLeft.append('g')
.attr('class', 'g-left-node');
function loadMindMap(parsed) {
var data = parsed;
var split_index = Math.round(data.children.length / 2);
parsedData = {
"name": data.name,
"children": JSON.parse(JSON.stringify(data.children.slice(split_index)))
};
var left = d3.hierarchy(parsedData, d => d.children);
drawLeft(left, "left");
}
// draw single tree
function drawLeft(root, pos) {
var SWITCH_CONST = 1;
if (pos === "left") SWITCH_CONST = -1;
update(root, SWITCH_CONST);
}
function update(source, SWITCH_CONST) {
var tree = d3.tree()
.size([heightMindMap, SWITCH_CONST * (widthMindMap - 150) / 2]);
var root = tree(source);
console.log(root)
var nodes = root.descendants();
var links = root.links();
console.log(nodes)
console.log(links)
// Set both root nodes to be dead center vertically
nodes[0].x = heightMindMap / 2
//JOIN new data with old elements
var link = gLeftLink.selectAll(".link-left")
.data(links, d => d)
.style('stroke-width', 1.5);
var linkEnter = link.enter().append("path")
.attr("class", "linkMindMap link-left")
.attr("d", d3.linkHorizontal()
.x(d => d.y)
.y(d => d.x));
var linkUpdate = linkEnter.merge(link);
linkUpdate.transition()
.duration(750)
var linkExit = link.exit()
.transition()
.duration(750)
.attr('x1', function(d) {
return root.x;
})
.attr('y1', function(d) {
return root.y;
})
.attr('x2', function(d) {
return root.x;
})
.attr('y2', function(d) {
return root.y;
})
.remove();
//JOIN new data with old elements
var node = gLeftNode.selectAll(".nodeMindMap-left")
.data(nodes, d => d);
console.log(nodes);
//ENTER new elements present in new data
var nodeEnter = node.enter().append("g").merge(node)
.attr("class", function(d) {
return "nodeMindMap-left " + "nodeMindMap" + (d.children ? " node--internal" : " node--leaf");
})
.classed("enter", true)
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
})
.attr("id", function(d) {
let str = d.data.name;
str = str.replace(/\s/g, '');
return str;
});
nodeEnter.append("circle")
.attr("r", function(d, i) {
return 2.5
});
var addLeftChild = nodeEnter.append("g")
.attr("class", "addHandler")
.attr("id", d => {
let str = d.data.name;
str = "addHandler-" + str.replace(/\s/g, '');
return str;
})
.style("opacity", "1")
.on("click", (d, i, nodes) => addNewLeftChild(d, i, nodes));
addLeftChild.append("line")
.attr("x1", -74)
.attr("y1", 1)
.attr("x2", -50)
.attr("y2", 1)
.attr("stroke", "#85e0e0")
.style("stroke-width", "2");
addLeftChild.append("rect")
.attr("x", "-77")
.attr("y", "-7")
.attr("height", 15)
.attr("width", 15)
.attr("rx", 5)
.attr("ry", 5)
.style("stroke", "#444")
.style("stroke-width", "1")
.style("fill", "#ccc");
addLeftChild.append("line")
.attr("x1", -74)
.attr("y1", 1)
.attr("x2", -65)
.attr("y2", 1)
.attr("stroke", "#444")
.style("stroke-width", "1.5");
addLeftChild.append("line")
.attr("x1", -69.5)
.attr("y1", -3)
.attr("x2", -69.5)
.attr("y2", 5)
.attr("stroke", "#444")
.style("stroke-width", "1.5");
// .call(d3.drag().on("drag", dragged));;
nodeEnter.append("foreignObject")
.style("fill", "blue")
.attr("x", -50)
.attr("y", -7)
.attr("height", "20px")
.attr("width", "100px")
.append('xhtml:div')
.append('div')
.attr("class", 'clickable-node')
.attr("id", function(d) {
let str = d.data.name;
str = "div-" + str.replace(/\s/g, '');
return str;
})
.attr("ondblclick", "this.contentEditable=true")
.attr("onblur", "this.contentEditable=false")
.attr("contentEditable", "false")
.style("text-align", "center")
.text(d => d.data.name);
//TODO: make it dynamic
nodeEnter.insert("rect", "foreignObject")
.attr("ry", 6)
.attr("rx", 6)
.attr("y", -10)
.attr("height", 20)
.attr("width", 100)
// .filter(function(d) { return d.flipped; })
.attr("x", -50)
.classed("selected", false)
.attr("id", function(d) {
let str = d.data.name;
str = "rect-" + str.replace(/\s/g, '');
return str;
});
var nodeUpdate = nodeEnter.merge(node);
// Transition to the proper position for the node
nodeUpdate.transition()
.duration(750)
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
});
// Remove any exiting nodes
var nodeExit = node.exit()
.transition()
.duration(750)
.attr("transform", function(d) {
return "translate(" + source.y + "," + source.x + ")";
})
.remove();
// On exit reduce the node circles size to 0
nodeExit.select('circle').attr('r', 0);
// node = nodeEnter.merge(node)
}
function addNewLeftChild(d, i, nodes) {
console.log("make new child");
event.stopPropagation();
var newNodeObj = {
// name: new Date().getTime(),
name: "New Child",
children: []
};
console.log("this is ", parsedData)
//Creates new Node
var newNode = d3.hierarchy(newNodeObj);
newNode.depth = d.depth + 1;
newNode.height = d.height - 1;
newNode.parent = d;
newNode.id = Date.now();
console.log(newNode);
console.log(d)
if (d.data.children.length == 0) {
console.log("i have no children")
d.children = []
}
d.children.push(newNode)
d.data.children.push(newNode.data)
console.log(d)
let foo = d3.hierarchy(parsedData, d => d.children)
drawLeft(foo, "left");
}
loadMindMap(parsedList);
There are a few things going on:
Using Unique Keys
Using names isn't the best for keys, because each new node has the same name ("New Child"). Instead it's probably better to use some sort of ID system. Here's a quick function to tag the data for each node with an ID.
let currNodeId = 0;
function idData(node) {
node.nodeId = ++currNodeId;
node.children.forEach(idData);
}
idData(parsedList);
And since you're redefining the data in parsedData, you need to use the id property there too:
parsedData = {
"name": data.name,
"nodeId": data.nodeId,
"children": JSON.parse(JSON.stringify(data.children.slice(split_index)))
};
When adding a new node, you can also set it in the nodeData:
var newNodeObj = {
// name: new Date().getTime(),
name: "New Child",
nodeId: ++currNodeId,
children: []
};
Then to actually use .nodeId as the key for nodes, use it as the key function:
.data(nodes, d => d.data.nodeId);
For links, you should use the target instead of the source, since this is a tree and there is only one link per child (instead of multiple links for one parent).
.data(nodes, d => d.target.data.nodeId);
Prevent multiple node elements from being added
There's also an issue where you're merging your new and old nodes before adding new elements. To prevent this, you should change
node.enter().append("g").merge(node)
to:
node.enter().append("g")
Link transitions
Finally the transitions for your links are not transitioning with the nodes. To make them transition, move:
.attr("d", d3.linkHorizontal()
.x(d => d.y)
.y(d => d.x));
to under
linkUpdate.transition()
.duration(750)
All together it looks like this: https://jsfiddle.net/v9wyb6q4/
Or:
const widthMindMap = 700;
const heightMindMap = 700;
let parsedData;
let parsedList = {
"name": " Stapler",
"children": [{
"name": " Bind",
"children": []
},
{
"name": " Nail",
"children": []
},
{
"name": " String",
"children": []
},
{
"name": " Glue",
"children": [{
"name": "Gum",
"children": []
},
{
"name": "Sticky Gum",
"children": []
}
]
},
{
"name": " Branch 3",
"children": []
},
{
"name": " Branch 4",
"children": [{
"name": " Branch 4.1",
"children": []
},
{
"name": " Branch 4.2",
"children": []
},
{
"name": " Branch 4.1",
"children": []
}
]
},
{
"name": " Branch 5",
"children": []
},
{
"name": " Branch 6",
"children": []
},
{
"name": " Branch 7",
"children": []
},
{
"name": " Branch 7.1",
"children": []
},
{
"name": " Branch 7.2",
"children": [{
"name": " Branch 7.2.1",
"children": []
},
{
"name": " Branch 7.2.1",
"children": []
}
]
}
]
}
let currNodeId = 0;
function idData(node) {
node.nodeId = ++currNodeId;
node.children.forEach(idData);
}
idData(parsedList);
let svgMindMap = d3.select('#div-mindMap')
.append("svg")
.attr("id", "svg-mindMap")
.attr("width", widthMindMap)
.attr("height", heightMindMap);
let backgroundLayer = svgMindMap.append('g')
.attr("width", widthMindMap)
.attr("height", heightMindMap)
.attr("class", "background")
let gLeft = backgroundLayer.append("g")
.attr("transform", "translate(" + widthMindMap / 2 + ",0)")
.attr("class", "g-left");
let gLeftLink = gLeft.append('g')
.attr('class', 'g-left-link');
let gLeftNode = gLeft.append('g')
.attr('class', 'g-left-node');
function loadMindMap(parsed) {
var data = parsed;
var split_index = Math.round(data.children.length / 2);
parsedData = {
"name": data.name,
"nodeId": data.nodeId,
"children": JSON.parse(JSON.stringify(data.children.slice(split_index)))
};
var left = d3.hierarchy(parsedData, d => d.children);
drawLeft(left, "left");
}
// draw single tree
function drawLeft(root, pos) {
var SWITCH_CONST = 1;
if (pos === "left") SWITCH_CONST = -1;
update(root, SWITCH_CONST);
}
function update(source, SWITCH_CONST) {
var tree = d3.tree()
.size([heightMindMap, SWITCH_CONST * (widthMindMap - 150) / 2]);
var root = tree(source);
console.log(root)
var nodes = root.descendants();
var links = root.links();
console.log(nodes)
console.log(links)
// Set both root nodes to be dead center vertically
nodes[0].x = heightMindMap / 2
//JOIN new data with old elements
var link = gLeftLink.selectAll(".link-left")
.data(links, d => d.target.data.nodeId)
.style('stroke-width', 1.5);
var linkEnter = link.enter().append("path")
.attr("class", "linkMindMap link-left");
var linkUpdate = linkEnter.merge(link);
linkUpdate.transition()
.duration(750)
.attr("d", d3.linkHorizontal()
.x(d => d.y)
.y(d => d.x));
var linkExit = link.exit()
.transition()
.duration(750)
.attr('x1', function(d) {
return root.x;
})
.attr('y1', function(d) {
return root.y;
})
.attr('x2', function(d) {
return root.x;
})
.attr('y2', function(d) {
return root.y;
})
.remove();
//JOIN new data with old elements
var node = gLeftNode.selectAll(".nodeMindMap-left")
.data(nodes, d => d.data.nodeId);
console.log(nodes);
//ENTER new elements present in new data
var nodeEnter = node.enter().append("g")
.attr("class", function(d) {
return "nodeMindMap-left " + "nodeMindMap" + (d.children ? " node--internal" : " node--leaf");
})
.classed("enter", true)
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
})
.attr("id", function(d) {
let str = d.data.name;
str = str.replace(/\s/g, '');
return str;
});
nodeEnter.append("circle")
.attr("r", function(d, i) {
return 2.5
});
var addLeftChild = nodeEnter.append("g")
.attr("class", "addHandler")
.attr("id", d => {
let str = d.data.name;
str = "addHandler-" + str.replace(/\s/g, '');
return str;
})
.style("opacity", "1")
.on("click", (d, i, nodes) => addNewLeftChild(d, i, nodes));
addLeftChild.append("line")
.attr("x1", -74)
.attr("y1", 1)
.attr("x2", -50)
.attr("y2", 1)
.attr("stroke", "#85e0e0")
.style("stroke-width", "2");
addLeftChild.append("rect")
.attr("x", "-77")
.attr("y", "-7")
.attr("height", 15)
.attr("width", 15)
.attr("rx", 5)
.attr("ry", 5)
.style("stroke", "#444")
.style("stroke-width", "1")
.style("fill", "#ccc");
addLeftChild.append("line")
.attr("x1", -74)
.attr("y1", 1)
.attr("x2", -65)
.attr("y2", 1)
.attr("stroke", "#444")
.style("stroke-width", "1.5");
addLeftChild.append("line")
.attr("x1", -69.5)
.attr("y1", -3)
.attr("x2", -69.5)
.attr("y2", 5)
.attr("stroke", "#444")
.style("stroke-width", "1.5");
// .call(d3.drag().on("drag", dragged));;
nodeEnter.append("foreignObject")
.style("fill", "blue")
.attr("x", -50)
.attr("y", -7)
.attr("height", "20px")
.attr("width", "100px")
.append('xhtml:div')
.append('div')
.attr("class", 'clickable-node')
.attr("id", function(d) {
let str = d.data.name;
str = "div-" + str.replace(/\s/g, '');
return str;
})
.attr("ondblclick", "this.contentEditable=true")
.attr("onblur", "this.contentEditable=false")
.attr("contentEditable", "false")
.style("text-align", "center")
.text(d => d.data.name);
//TODO: make it dynamic
nodeEnter.insert("rect", "foreignObject")
.attr("ry", 6)
.attr("rx", 6)
.attr("y", -10)
.attr("height", 20)
.attr("width", 100)
// .filter(function(d) { return d.flipped; })
.attr("x", -50)
.classed("selected", false)
.attr("id", function(d) {
let str = d.data.name;
str = "rect-" + str.replace(/\s/g, '');
return str;
});
var nodeUpdate = nodeEnter.merge(node);
// Transition to the proper position for the node
nodeUpdate.transition()
.duration(750)
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
});
// Remove any exiting nodes
var nodeExit = node.exit()
.transition()
.duration(750)
.attr("transform", function(d) {
return "translate(" + source.y + "," + source.x + ")";
})
.remove();
// On exit reduce the node circles size to 0
nodeExit.select('circle').attr('r', 0);
// node = nodeEnter.merge(node)
}
function addNewLeftChild(d, i, nodes) {
console.log("make new child");
event.stopPropagation();
var newNodeObj = {
// name: new Date().getTime(),
name: "New Child",
nodeId: ++currNodeId,
children: []
};
console.log("this is ", parsedData)
//Creates new Node
var newNode = d3.hierarchy(newNodeObj);
newNode.depth = d.depth + 1;
newNode.height = d.height - 1;
newNode.parent = d;
newNode.id = Date.now();
console.log(newNode);
console.log(d)
if (d.data.children.length == 0) {
console.log("i have no children")
d.children = []
}
d.children.push(newNode)
d.data.children.push(newNode.data)
console.log(d)
let foo = d3.hierarchy(parsedData, d => d.children)
drawLeft(foo, "left");
}
loadMindMap(parsedList);
.linkMindMap {
fill: none;
stroke: #555;
stroke-opacity: 0.4;
}
rect {
fill: white;
stroke: #3182bd;
stroke-width: 1.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<div id="div-mindMap">
These sorts of problems usually arise because the key function which you pass as the second parameter to selection.data() is not unique or "too unique".
It should return a simple value which uniquely identifies each datum. In your case
.data(nodes, d => d);
might be better as
.data(nodes, d => d.name);
and similarly for the links.
However you will need to examine the output of d3.tree to see what fields the nodes and links have and which field contains a unique id.
Related
I struggle to properly redraw the provided D3 forced graph. As soon as I delete a node, which is NOT the last node, the binding/assignment between link and node is broken. The belonged linktext is either wrong or written on top of an existing.
What I am doing?
On node click I retrieve the node id, which I use to retrieve the correct link array index, by comparing them the source.id and to find the correct node array index position too. Further I use the results to finally splice the link and node array at the correct position.
So whats my problem?
For example I delete node number 3, which should delete the node array object at position 2, which is true. Further the link between 3 --- 1 should be removed from the link array object at position 1 as well, which is also true.
At the end I restart the data assignment and call the restart() function. Which should use the modified nodes and links array´s to merge and redraw the graph. It actually does redraw but the link text is wrong.. instead of node 3 node 5 was deleted.
Help.
var data = {
"nodes": [{
"id": 1
},
{
"id": 2,
},
{
"id": 3,
},
{
"id": 4,
},
{
"id": 5,
}
],
"links": [{
"source": 2,
"target": 1,
"text": "2 --- 1"
},
{
"source": 3,
"target": 1,
"text": "3 --- 1"
},
{
"source": 4,
"target": 1,
"text": "4 --- 1"
},
{
"source": 5,
"target": 1,
"text": "5 --- 1"
}
]
};
let nodes = data.nodes
let links = data.links
//Helper
let nodeToDelete
var width = window.innerWidth,
height = window.innerHeight;
var buttons = d3.select("body").selectAll("button")
.data(["add node", "remove node"])
.enter()
.append("button")
.attr("class", "buttons")
.text(function (d) {
return d;
})
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.call(d3.zoom().on("zoom", function (event) {
svg.attr("transform", event.transform)
}))
.append("g")
var simulation = d3.forceSimulation()
.force("size", d3.forceCenter(width / 2, height / 2))
.force("charge", d3.forceManyBody().strength(-5000))
.force("link", d3.forceLink().id(function (d) {
return d.id
}).distance(250))
linksContainer = svg.append("g").attr("class", "linkscontainer")
nodesContainer = svg.append("g").attr("class", "nodesContainer")
console.log("links_on_init", links)
console.log("nodes_on_init", nodes)
restart()
simulation
.nodes(nodes)
.on("tick", tick)
simulation
.force("link").links(links)
function tick() {
linkLine.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;
})
node
.attr("transform", d => `translate(${d.x}, ${d.y})`);
}
function dragStarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragEnded(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
buttons.on("click", function (_, d) {
if (d === "add node") {
const newObj = { "id": nodes.length + 1,}
const newLink = {"source": nodes.length + 1, "target": 1, "text": nodes.length + 1 + " --- " + "1"}
nodes.push(newObj)
links.push(newLink)
} else if (d === "remove node") {
if (nodeToDelete != undefined) {
let linkToDeleteIndex = links.findIndex(obj => obj.source.id === nodeToDelete.id )
let nodeToDeleteIndex = nodes.findIndex(obj => obj.id === nodeToDelete.id)
links.splice(linkToDeleteIndex, 1)
nodes.splice(nodeToDeleteIndex, 1)
console.log("links_after_removal", links)
console.log("nodes_after_removal", nodes)
}
}
restart()
})
function restart() {
// Update linkLines
linkLine = linksContainer.selectAll(".linkPath")
.data(links)
linkLine.exit().remove()
const linkLineEnter = linkLine.enter()
.append("path")
.attr("class", "linkPath")
.attr("stroke", "red")
.attr("fill", "transparent")
.attr("stroke-width", 3)
.attr("id", function (_, i) {
return "path" + i
})
linkLine = linkLineEnter.merge(linkLine)
// Update linkText
linkText = linksContainer.selectAll("linkLabel")
.data(links)
linkText.exit().remove()
const linkTextEnter = linkText.enter()
.append("text")
.attr("dy", -10)
.attr("class", "linkLabel")
.attr("id", function (d, i) { return "linkLabel" + i })
.attr("text-anchor", "middle")
.text("")
linkTextEnter.append("textPath")
.attr("xlink:href", function (_, i) {
return "#path" + i
})
.attr("startOffset", "50%")
.attr("opacity", 0.75)
.attr("cursor", "default")
.attr("class", "linkText")
.attr("color", "black")
.text(function (d) {
return d.text
})
linkText = linkTextEnter.merge(linkText)
// Update nodes
node = nodesContainer.selectAll(".nodes")
.data(nodes)
node.exit().remove()
const nodesEnter = node.enter()
.append("g")
.attr("class", "nodes")
.call(d3.drag()
.on("start", dragStarted)
.on("drag", dragged)
.on("end", dragEnded)
)
nodesEnter.selectAll("circle")
.data(d => [d])
.enter()
.append("circle")
.style("stroke", "blue")
.attr("r", 40)
.on("click", function(_, d) {
d3.selectAll("circle")
.attr("fill", "whitesmoke")
d3.select(this)
.attr("fill", "red")
nodeToDelete = d
})
nodesEnter.append("text")
.attr("dominant-baseline", "central")
.attr("text-anchor", "middle")
.attr("font-size", 20)
.attr("fill", "black")
.attr("pointer-events", "none")
.text(function (d) {
return d.id
})
node = nodesEnter.merge(node)
// Update and restart the simulation.
simulation
.nodes(nodes);
simulation
.force("link")
.links(links)
simulation.restart().alpha(1)
}
.link {
stroke: #000;
stroke-width: 1.5px;
}
.nodes {
fill: whitesmoke;
}
.buttons {
margin: 0 1em 0 0;
}
<!DOCTYPE html>
<html lang="de">
<head>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
<meta charset="utf-8">
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.3.js"></script>
<!-- D3 -->
<script src="https://d3js.org/d3.v7.min.js"></script>
<!-- fontawesome stylesheet https://fontawesome.com/ -->
<script src="https://kit.fontawesome.com/98a5e27706.js" crossorigin="anonymous"></script>
</head>
<body>
</body>
</html>
You should provide data keys when you do .data(data). So for example when you provide data to the nodes, you may pass key like this:
node = nodesContainer.selectAll(".nodes")
.data(nodes, node => node.id) // Pass node.id as a key so d3 knows which node is a new and which one is old.
You can read about this here - https://observablehq.com/#dnarvaez27/understanding-enter-exit-merge-key-function
Also you've forgot to place . before class name when you adding text labels to the graph, that is why text was duplicated )
Here fixed example, but since you are using array length as ids, there will be duplicates in ids for nodes and links, it will lead to unexpected results, I consider to use uniq ids rather then indexes.
var data = {
"nodes": [{
"id": 1
},
{
"id": 2,
},
{
"id": 3,
},
{
"id": 4,
},
{
"id": 5,
}
],
"links": [{
"source": 2,
"target": 1,
"text": "2 --- 1"
},
{
"source": 3,
"target": 1,
"text": "3 --- 1"
},
{
"source": 4,
"target": 1,
"text": "4 --- 1"
},
{
"source": 5,
"target": 1,
"text": "5 --- 1"
}
]
};
let nodes = data.nodes
let links = data.links
//Helper
let nodeToDelete
var width = window.innerWidth,
height = window.innerHeight;
var buttons = d3.select("body").selectAll("button")
.data(["add node", "remove node"])
.enter()
.append("button")
.attr("class", "buttons")
.text(function (d) {
return d;
})
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.call(d3.zoom().on("zoom", function (event) {
svg.attr("transform", event.transform)
}))
.append("g")
var simulation = d3.forceSimulation()
.force("size", d3.forceCenter(width / 2, height / 2))
.force("charge", d3.forceManyBody().strength(-5000))
.force("link", d3.forceLink().id(function (d) {
return d.id
}).distance(250))
linksContainer = svg.append("g").attr("class", "linkscontainer")
nodesContainer = svg.append("g").attr("class", "nodesContainer")
console.log("links_on_init", links)
console.log("nodes_on_init", nodes)
restart()
simulation
.nodes(nodes)
.on("tick", tick)
simulation
.force("link").links(links)
function tick() {
linkLine.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;
})
node
.attr("transform", d => `translate(${d.x}, ${d.y})`);
}
function dragStarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragEnded(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
buttons.on("click", function (_, d) {
if (d === "add node") {
const newObj = { "id": nodes.length + 1,}
const newLink = {"source": nodes.length + 1, "target": 1, "text": nodes.length + 1 + " --- " + "1"}
nodes.push(newObj)
links.push(newLink)
} else if (d === "remove node") {
if (nodeToDelete != undefined) {
let linkToDeleteIndex = links.findIndex(obj => obj.source.id === nodeToDelete.id )
let nodeToDeleteIndex = nodes.findIndex(obj => obj.id === nodeToDelete.id)
links.splice(linkToDeleteIndex, 1)
nodes.splice(nodeToDeleteIndex, 1)
console.log("links_after_removal", links)
console.log("nodes_after_removal", nodes)
}
}
restart()
})
function restart() {
// Update linkLines
linkLine = linksContainer.selectAll(".linkPath")
.data(links, link => link.text) // ADD DATA KEY FOR LINK
linkLine.exit().remove()
const linkLineEnter = linkLine.enter()
.append("path")
.attr("class", "linkPath")
.attr("stroke", "red")
.attr("fill", "transparent")
.attr("stroke-width", 3)
.attr("id", function (_, i) {
return "path" + i
})
linkLine = linkLineEnter.merge(linkLine)
// Update linkText
linkText = linksContainer.selectAll(".linkLabel") // FIXED ClassName
.data(links, link => link.text) // ADD DATA KEY FOR TEXT
linkText.exit().remove()
const linkTextEnter = linkText.enter()
.append("text")
.attr("dy", -10)
.attr("class", "linkLabel")
.attr("id", function (d, i) { return "linkLabel" + i })
.attr("text-anchor", "middle")
.text("")
linkTextEnter.append("textPath")
.attr("xlink:href", function (_, i) {
return "#path" + i
})
.attr("startOffset", "50%")
.attr("opacity", 0.75)
.attr("cursor", "default")
.attr("class", "linkText")
.attr("color", "black")
.text(function (d) {
return d.text
})
linkText = linkTextEnter.merge(linkText)
// Update nodes
node = nodesContainer.selectAll(".nodes")
.data(nodes, node => node.id) // ADD DATA KEY FOR NODE
node.exit().remove()
const nodesEnter = node.enter()
.append("g")
.attr("class", "nodes")
.call(d3.drag()
.on("start", dragStarted)
.on("drag", dragged)
.on("end", dragEnded)
)
nodesEnter.selectAll("circle")
.data(d => [d])
.enter()
.append("circle")
.style("stroke", "blue")
.attr("r", 40)
.on("click", function(_, d) {
d3.selectAll("circle")
.attr("fill", "whitesmoke")
d3.select(this)
.attr("fill", "red")
nodeToDelete = d
})
nodesEnter.append("text")
.attr("dominant-baseline", "central")
.attr("text-anchor", "middle")
.attr("font-size", 20)
.attr("fill", "black")
.attr("pointer-events", "none")
.text(function (d) {
return d.id
})
node = nodesEnter.merge(node)
// Update and restart the simulation.
simulation
.nodes(nodes);
simulation
.force("link")
.links(links)
simulation.restart().alpha(1)
}
.link {
stroke: #000;
stroke-width: 1.5px;
}
.nodes {
fill: whitesmoke;
}
.buttons {
margin: 0 1em 0 0;
}
<!DOCTYPE html>
<html lang="de">
<head>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
<meta charset="utf-8">
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.3.js"></script>
<!-- D3 -->
<script src="https://d3js.org/d3.v7.min.js"></script>
<!-- fontawesome stylesheet https://fontawesome.com/ -->
<script src="https://kit.fontawesome.com/98a5e27706.js" crossorigin="anonymous"></script>
</head>
<body>
</body>
</html>
I'm trying to display a network graph with clustered nodes but I'm having trouble with the nested nodes in D3. The first "layer" contains clusters and each node of the first layer can contain multiple nodes. Links in the network would probably only occur between clusters (meaning between nodes of the first layer).
Here is the code I have so far. I'm able to display the first level of nodes. I cannot figure out how to display the nested nodes (see code in const data in each node children).
const node_radius = 100;
const width = 800;
const height = 400;
const links = [
{ "source": 1, "target": 6}
] ;
const data = [
{
"id":1,
"level": "cluster",
"name": "analytics1",
"children": [
{
"id":2,
"name": "animate1",
"level": "leaf",
"size": 15,
"parent": 1
},
{
"id":3,
"name": "animate2",
"level": "leaf",
"size": 15,
"parent": 1
},
{
"id":4,
"name": "animate3",
"level": "leaf",
"size": 15,
"parent": 1
}
]
},
{
"id":6,
"name": "analytics2",
"level": "cluster",
"children": [
{
"id":7,
"name": "animate4",
"level": "leaf",
"size": 10,
"parent": 6
}
]
}
]
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var simulation = d3.forceSimulation()
// pull nodes together based on the links between them
.force("link", d3.forceLink().id(function(d) { return d.id; }).strength(0.0001))
// push nodes apart to space them out
.force("charge", d3.forceManyBody().strength(-10))
// add some collision detection so they don't overlap
.force("collide", d3.forceCollide().radius(node_radius))
// and draw them around the centre of the space
.force("center", d3.forceCenter(width / 2, height / 2));
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(links).enter().append("line")
.attr("stroke-width", 5)
.attr("stroke","#000");
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("id", function(d) {return "circle"+d.id;})
.attr("class", "node")
.attr("r", node_radius)
.style("opacity", 0.2)
.attr("dx", 12)
.attr("dy", ".35em");
var text = svg.append("g")
.attr("class", "label")
.selectAll("text")
.data(data)
.enter().append("text")
.text(function(d) { return d.name });
// Update and restart the simulation.
simulation.nodes(data).on("tick", ticked);
simulation.force("link").links(links);
simulation.alpha(1).restart();
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("transform", positionNode);
text
.attr("dx", function(d) { return d.x - 30; })
.attr("dy", function(d) { return d.y + 15; });
}
// move the node based on forces calculations
function positionNode(d) {
// keep the node within the boundaries of the svg
if (d.x < node_radius) {
d.x = 2*node_radius
};
if (d.y < node_radius) {
d.y = 2*node_radius
};
if (d.x > width-node_radius) {
d.x = width-(2*node_radius)
};
if (d.y > height-node_radius) {
d.y = height-(2*node_radius)
};
return "translate(" + d.x + "," + d.y + ")";
}
<script src="https://d3js.org/d3.v4.min.js"></script>
I would like to have something like the following image. The two clusters are displayed and in each group, all children (leaf nodes) are represented by a smaller node. Node size should be customizable for both "layers" from data input.
Example I'm trying to follow on Fiddle.
I have also tried to use d3.pack() to pack circles inside of other circles. Here is an example. The problem I have currently with this approach is that I did not succeed in adding space and links between nodes of the first "layer" (between clusters). The high level clusters are also packed together and it would be impossible to add comprehensible links betwen them.
I finally succeeded in merging the d3.pack() example with the clustering example. Here is my solution.
var data = [
{
"id":1,
"level": "cluster",
"name": "analytics1",
"children": [
{
"id":2,
"name": "animate1",
"level": "leaf",
"size": 8,
"parent": 1,
"icon":"https://image.freepik.com/free-icon/apple-logo_318-40184.jpg"
},
{
"id":3,
"name": "animate2",
"level": "leaf",
"size": 10,
"parent": 1,
"icon": "https://www.freelogodesign.org/img/logo-ex-7.png"
},
{
"id":4,
"name": "animate3",
"level": "leaf",
"size": 5,
"parent": 1,
"icon": "http://brandmark.io/logo-rank/random/pepsi.png"
}
]
},
{
"id":6,
"name": "analytics2",
"level": "cluster",
"children": [
{
"id":7,
"name": "animate4",
"level": "leaf",
"size": 10,
"parent": 6,
"icon":"https://www.seoclerk.com/pics/558390-11FO8A1505384509.png"
}
]
}
]
var links = [
{ "source": 1, "target": 6}
] ;
var w = 1200, h = 500;
var cluster_padding = 5;
var node_padding = 2;
var size_ratio =100;
var color = d3.scaleOrdinal(d3.schemeCategory20c);
let sumSizes = 0;
data.forEach(function(cluster){
cluster.children.forEach(function(node){
sumSizes += node.size;
});
});
// Compute sum of sizes for cluster size.
data.forEach(function(cluster){
cluster.size = (
cluster.children.map(function(d){return d.size;})
.reduce(function(acc, val){ return acc+val+node_padding; })/sumSizes
)*size_ratio + cluster_padding;
cluster.children = cluster.children.sort(function(a,b){
return (a.size < b.size) ? 1 : ((b.size < a.size) ? -1 : 0);
})
cluster.children.forEach(function(node){
node.parentSize = cluster.size;
node.size = node.size*size_ratio/sumSizes;
});
});
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
////////////////////////
// outer force layout
var outerSimulation = d3.forceSimulation()
// pull nodes together based on the links between them
.force("link", d3.forceLink().id(function(d) { return d.id; }).strength(0.001))
// push nodes apart to space them out
.force("charge", d3.forceManyBody().strength(-5))
// add some collision detection so they don't overlap
.force("collide", d3.forceCollide().radius(function(d){return d.size+cluster_padding;}))
// and draw them around the centre of the space
.force("center", d3.forceCenter(w / 2, h / 2));
var outerLinks = svg.selectAll("line")
.data(links)
.enter().append("line")
.attr("class", "links")
.attr("stroke-width", 5);
var outerNodes = svg.selectAll("g.outer")
.data(data, function (d) {return d.id;})
.enter()
.append("g")
.attr("class", "outer")
.attr("id", function (d) {return "cluster"+d.id;})
.attr("x", w/2)
.attr("y", w/2)
.call(d3.drag());
outerNodes.append("circle")
.style("fill", function(d,i){return color(i);})
.style("stroke", "blue")
.attr("r", function(d){return d.size});
// Update and restart the simulation.
outerSimulation.nodes(data).on("tick", outerTick);
outerSimulation.force("link").links(links);
outerSimulation.alpha(1).restart();
////////////////////////
// inner force layouts
var innerNodes = [];
var innerTexts = [];
var packs = [];
var margin = 20;
data.forEach(function(n){
// Pack hierarchy definition
var pack = d3.pack()
.size([2*n.size, 2*n.size])
.padding(cluster_padding);
var root = d3.hierarchy(n)
.sum(function(d) { return d.size; })
.sort(function(a, b) { return b.value - a.value; });
var nodes = pack(root).descendants();
// Round images
var defs = svg.append("defs").attr("id", "imgdefs")
var pattern = defs
.selectAll("pattern")
.data(nodes.filter(function(d) { return d.parent }))
.enter().append("pattern")
.attr("id", function(d){return "photo"+d.data.name})
.attr("height", 1)
.attr("width", 1)
.attr("x", "0")
.attr("y", "0");
var image = pattern.append('image')
.attr("class","roundImg")
.attr("id", function(d){return "photo"+d.data.name;})
.attr("xlink:href", function(d){return d.data.icon ? d.data.icon : "";})
.attr("height", function(d){return 3.2*d.r ;})
;
// Nodes
var circle = svg.select("g.outer#cluster"+n.id).selectAll("g.inner")
.data(nodes.filter(function(d) { return d.parent }))
.enter().append("circle")
.attr("class", "node node--leaf ")
.attr("id", function(d) {return d.data.name})
.style("fill", function(d) { return "url(#photo"+d.data.name+")";})
.attr("r", function(d) { return d.r; })
.attr("transform", function(d) { return "translate("+(d.x-n.size) +","+ (d.y-n.size)+")"; })
;
});
////////////////////////
// functions
function outerTick (e) {
outerNodes.attr("transform", positionNode);
outerLinks
.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 positionNode(d) {
// keep the node within the boundaries of the svg
if (d.x - d.size < 0) {
d.x = d.size + 2
};
if (d.y - d.size < 0) {
d.y = d.size + 2
};
if (d.x + d.size > w) {
d.x = w - d.size - 2
};
if (d.y + d.size > h) {
d.y = h - d.size - 2
};
return "translate(" + d.x + "," + d.y + ")";
}
<!DOCTYPE html>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/pack.css">
<body>
<div class="packed" id="packed"></div>
</body>
I found out that the data I'm trying to show with a chart gets a little messy with all the labels, so I thought I'd add a method that hides the <text> tags of all the pie slices except for the one you are hovering over. The <text> tags have classes corresponding to which child they are:
function visibilityShow(dataSetSize) {
for (var i = 0; i < dataSetSize; i++) {
$("#" + i).show();
}
}
function visibilityHide(index, dataSetSize) {
for (var i = 0; i < dataSetSize; i++) {
if (i === index) {
$("#" + i).show();
} else {
$("#" + i).hide();
}
}
}
Then pass it in on hover:
.on("mouseover.arcExpand", arcTween(outerRadius, 0))
.on("mouseover.textHide", function (d, i) {
visibilityHide(i, dataSet.length);
})
.on("mouseout.arcRetract", arcTween(outerRadius - 20, 150))
.on("mouseout.textShow", function (d, i) {
visibilityShow(dataSet.length);
});
Now it turns out that I'm passing in 0 for i because of the way I pass in data:
newSlices.select("path")
.each(function (d) { d.outerRadius = outerRadius - 20; })
//.transition()
.attr("d", arc)
.attr("fill", function (d, i) { return newColor(i); })
.attr("title", function (d) { return d["value"]; });
newSlices.selectAll("path")
.on("click", function (d) {
checkForChild(d["data"]["label"], d["data"]);
})
.on("mouseover.arcExpand", arcTween(outerRadius, 0))
.on("mouseover.textHide", function (d, i) {
visibilityHide(i, dataSet.length);
})
.on("mouseout.arcRetract", arcTween(outerRadius - 20, 150))
.on("mouseout.textShow", function (d, i) {
visibilityShow(dataSet.length);
});
If you run the code snippet you see that the issue that the code only ever hides the text tag with class "0." How do I set up the on mouseover event so that I can try to hide the correct tags?
// This data will be gathered from API calls eventually
dataDefault = [];
dataController = [{ "label": "Example 1", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
{ "label": "Example 2", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
{ "label": "Example 3", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
{ "label": "Example 4", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
{ "label": "Example 5", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] }];
var displaySize = 20;
// This is used to keep track of what data is showing
var mode = "Default";
// The amount of pixels the SVG will take up
var width = 600,
height = 675;
// It's a donut, so it has an outer radius and an inner radius. 2r = width so r = width/2
var outerRadius = width / 2,
innerRadius = outerRadius / 3;
// Default color function for deciding the colros of the donut slices
var color = d3.scale.category10();
// The pie function for deciding the size of the donut slices
var pie = d3.layout.pie()
.value(function (d) { return d["value"]; });
// At first we use the default data to create the pie
var pieData = pie(dataDefault);
// Create an arc
var arc = d3.svg.arc()
.innerRadius(innerRadius);
// Add an SVG tag to the document
var svg = d3.select("#graphs").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + outerRadius + "," + (outerRadius + 50) + ")");
// Append an link tag for each point of the data, then add an path tag inside each a tag
svg.selectAll("a")
.data(pieData)
.enter().append("a")
.append("path")
.each(function (d) { d.outerRadius = outerRadius - 20; })
.attr("d", arc)
.attr("fill", function (d, i) { return color(i); })
.on("mouseover", arcTween(outerRadius, 0, 0))
.on("mouseout", arcTween(outerRadius - 20, 150))
.append("title")
.text(function (d) { return d["value"] + " hits"; });
// Change the default data to the Apps data so it animates on load
changeToAPI("Controller", dataController);
// Function used to increase slice size on hover
function arcTween(outerRadius, delay) {
return function () {
d3.select(this).transition().delay(delay).attrTween("d", function (d) {
var i = d3.interpolate(d.outerRadius, outerRadius);
return function (t) { d.outerRadius = i(t); return arc(d); };
});
};
}
// Passes the color scale into the change function
function getColor(name) {
// Get the remainder when / 3
var bucket = hashify(name) % 4;
// Setup the array of color functions
var colors = [d3.scale.category10(), d3.scale.category20(), d3.scale.category20b(), d3.scale.category20c()];
// Return the correct bucket
return colors[bucket];
}
// Function used to swap the data being shown
function changeToAPI(name, dataSet) {
// Don't update if the data is already showing
// JavaScript doesn't short circuit?
if (dataSet === null) {
dataSet = [{ "label": "No data...", "value": 1 }];
changeTo(name, dataSet);
} else if (dataSet.length === 0) {
dataSet = [{ "label": "No data...", "value": 1 }];
changeTo(name, dataSet);
} else {
mode = name;
// Get the new pie and color functions
var newData = pie(dataSet);
var newColor = getColor(name);
// Remove the labels, titles, and tooltips
svg.selectAll("text").remove();
svg.selectAll("title").remove();
// Line below fixes an error that doesn't cause issues, but makes the graph ugly :(
svg.selectAll("a").remove();
// Add the new slices if there are any
var newSlices = svg.selectAll("a")
.data(newData);
newSlices.enter()
.append("a")
.append("path")
.style("cursor", "pointer");
// Update the attributes of those slices and animate the transition
newSlices.select("path")
.each(function (d) { d.outerRadius = outerRadius - 20; })
.transition()
.attr("d", arc)
.attr("fill", function (d, i) { return newColor(i); })
.attr("title", function (d) { return d["value"]; });
newSlices.selectAll("path")
.on("click", function (d) {
checkForChild(d["data"]["label"], d["data"]);
})
.on("mouseover.arcExpand", arcTween(outerRadius, 0))
.on("mouseover.textHide", function (d, i) {
visibilityHide(i, dataSet.length);
})
.on("mouseout.arcRetract", arcTween(outerRadius - 20, 150))
.on("mouseout.textShow", function (d, i) {
visibilityShow(dataSet.length);
});
// Remove excess slices
newSlices.exit().remove();
// Add a title
var title = svg.append("text")
.attr("x", 0)
.attr("y", -(outerRadius + 10))
.style("text-anchor", "middle")
.text("Distrubution of " + name + " Usage");
// Add labels
var labels = svg.selectAll(null)
.data(newData)
.enter()
.append("text")
.attr("fill", "white")
.attr("id", function (d, i) { return i })
.attr("transform", function (d) {
d.innerRadius = 0;
d.outerRadius = outerRadius;
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function (d, i) {
return dataSet[i]["label"];
});
// Add tooltips
svg.selectAll("path").data(newData).append("title").text(function (d) { return d["value"] + " hits"; });
svg.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", innerRadius)
.style("fill", "white")
.style("cursor", "pointer")
.on("click", function () {
changeToAPI("Controller", dataController);
});
// Adds back button if not at controller level
if (dataSet !== dataController) {
svg.append("text")
.attr("x", 0)
.attr("y", 12)
.style("text-anchor", "middle")
.style("color", "#efefef")
.style("font-size", "40px")
.text("Back");
}
}
}
function changeTo(name, dataSet) {
// Don't update if the data is already showing
// JavaScript doesn't short circuit?
if (dataSet === null) {
dataSet = [{ "label": "No data...", "value": 1 }];
} else if (dataSet.length === 0) {
dataSet = [{ "label": "No data...", "value": 1 }];
}
mode = name;
// Get the new pie and color functions
var newData = pie(dataSet);
var newColor = getColor(name);
// Remove the labels, titles, and tooltips
svg.selectAll("text").remove();
svg.selectAll("title").remove();
// Line below fixes an error that doesn't cause issues, but makes the graph ugly :(
//svg.selectAll("a").remove();
// Add the new slices if there are any
var newSlices = svg.selectAll("a")
.data(newData);
newSlices.enter()
.append("a")
.append("path")
.style("cursor", "pointer");
// Update the attributes of those slices and animate the transition
newSlices.select("path")
.each(function (d) { d.outerRadius = outerRadius - 20; })
.transition()
.attr("fill", function (d, i) { return newColor(i); })
.attr("d", arc)
.attr("title", function (d) { return d["value"]; });
newSlices.selectAll("path")
.on("mouseover.arc", arcTween(outerRadius, 0))
.on("mouseover.text", function (d, i) {
visibilityHide(i, dataSet.length);
})
.on("mouseout.arc", arcTween(outerRadius - 20, 150))
.on("mouseout.text", function (d, i) {
visibilityShow(dataSet.length);
});
// Remove excess slices
newSlices.exit().remove();
// Add a title
svg.append("text")
.attr("x", 0)
.attr("y", -(outerRadius + 10))
.style("text-anchor", "middle")
.text(function (e) {
var title = "Distrubution of " + name + " Usage";
if (name === "Defualt") {
title = "Loading..."
}
return title;
});
// Add labels
svg.selectAll(null)
.data(newData)
.enter()
.append("text")
.attr("fill", "white")
.attr("id", function (d, i) { return i })
.attr("transform", function (d) {
d.innerRadius = 0;
d.outerRadius = outerRadius;
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function (d, i) {
return dataSet[i]["label"];
});
// Add tooltips
svg.selectAll("path").data(newData).append("title").text(function (d) { return d["value"] + " hits"; });
}
function checkForChild(name, dataSet) {
if (dataSet.hasOwnProperty("child")) {
if (dataSet["child"] !== null) {
if (dataSet["child"].length !== 0) {
changeToAPI(name, dataSet["child"]);
}
}
}
}
// Hashcode generator for strings
function hashify(string) {
var hash = 0;
// Add the value of each char to the hash value
for (var i = 0; i < string.length; i++) {
hash += string.charCodeAt(i);
}
return hash;
}
function visibilityShow(dataSetSize) {
for (var i = 0; i < dataSetSize; i++) {
$("#" + i).show();
}
}
function visibilityHide(index, dataSetSize) {
for (var i = 0; i < dataSetSize; i++) {
if (i === index) {
$("#" + i).show();
} else {
$("#" + i).hide();
}
}
}
body {
font-family: Arial;
transition: all ease .5s;
text-align: center;
color: rgb(58,58,58);
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>General Statistics</title>
</head>
<body>
<div id="graphs">
</div>
</body>
</html>
Thanks!
The reason is, as you stated, that i is giving you 0 whenever you hover the path. What you can do is simple: when you are iterating through your data using .each(), you can simply bind the index to a property, e.g.:
newSlices.select("path")
.each(function (d, i) {
d.index = i;
d.outerRadius = outerRadius - 20;
})
By doing that, whenever you hover over each <path> again, its index will be accessible via the d.index property:
newSlices.selectAll("path")
.on("mouseover.textHide", function (d) {
// Index was stored in the `index` key
visibilityHide(d.index, dataSet.length);
})
// This data will be gathered from API calls eventually
dataDefault = [];
dataController = [{ "label": "Example 1", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
{ "label": "Example 2", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
{ "label": "Example 3", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
{ "label": "Example 4", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
{ "label": "Example 5", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] }];
var displaySize = 20;
// This is used to keep track of what data is showing
var mode = "Default";
// The amount of pixels the SVG will take up
var width = 600,
height = 675;
// It's a donut, so it has an outer radius and an inner radius. 2r = width so r = width/2
var outerRadius = width / 2,
innerRadius = outerRadius / 3;
// Default color function for deciding the colros of the donut slices
var color = d3.scale.category10();
// The pie function for deciding the size of the donut slices
var pie = d3.layout.pie()
.value(function (d) { return d["value"]; });
// At first we use the default data to create the pie
var pieData = pie(dataDefault);
// Create an arc
var arc = d3.svg.arc()
.innerRadius(innerRadius);
// Add an SVG tag to the document
var svg = d3.select("#graphs").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + outerRadius + "," + (outerRadius + 50) + ")");
// Append an link tag for each point of the data, then add an path tag inside each a tag
svg.selectAll("a")
.data(pieData)
.enter().append("a")
.append("path")
.each(function (d) { d.outerRadius = outerRadius - 20; })
.attr("d", arc)
.attr("fill", function (d, i) { return color(i); })
.on("mouseover", arcTween(outerRadius, 0, 0))
.on("mouseout", arcTween(outerRadius - 20, 150))
.append("title")
.text(function (d) { return d["value"] + " hits"; });
// Change the default data to the Apps data so it animates on load
changeToAPI("Controller", dataController);
// Function used to increase slice size on hover
function arcTween(outerRadius, delay) {
return function () {
d3.select(this).transition().delay(delay).attrTween("d", function (d) {
var i = d3.interpolate(d.outerRadius, outerRadius);
return function (t) { d.outerRadius = i(t); return arc(d); };
});
};
}
// Passes the color scale into the change function
function getColor(name) {
// Get the remainder when / 3
var bucket = hashify(name) % 4;
// Setup the array of color functions
var colors = [d3.scale.category10(), d3.scale.category20(), d3.scale.category20b(), d3.scale.category20c()];
// Return the correct bucket
return colors[bucket];
}
// Function used to swap the data being shown
function changeToAPI(name, dataSet) {
// Don't update if the data is already showing
// JavaScript doesn't short circuit?
if (dataSet === null) {
dataSet = [{ "label": "No data...", "value": 1 }];
changeTo(name, dataSet);
} else if (dataSet.length === 0) {
dataSet = [{ "label": "No data...", "value": 1 }];
changeTo(name, dataSet);
} else {
mode = name;
// Get the new pie and color functions
var newData = pie(dataSet);
var newColor = getColor(name);
// Remove the labels, titles, and tooltips
svg.selectAll("text").remove();
svg.selectAll("title").remove();
// Line below fixes an error that doesn't cause issues, but makes the graph ugly :(
svg.selectAll("a").remove();
// Add the new slices if there are any
var newSlices = svg.selectAll("a")
.data(newData);
newSlices.enter()
.append("a")
.append("path")
.style("cursor", "pointer");
// Update the attributes of those slices and animate the transition
newSlices.select("path")
.each(function (d, i) {
d.index = i;
d.outerRadius = outerRadius - 20; })
.transition()
.attr("d", arc)
.attr("fill", function (d, i) { return newColor(i); })
.attr("title", function (d) { return d["value"]; });
newSlices.selectAll("path")
.on("click", function (d) {
checkForChild(d["data"]["label"], d["data"]);
})
.on("mouseover.arcExpand", arcTween(outerRadius, 0))
.on("mouseover.textHide", function (d) {
visibilityHide(d.index, dataSet.length);
})
.on("mouseout.arcRetract", arcTween(outerRadius - 20, 150))
.on("mouseout.textShow", function (d) {
visibilityShow(dataSet.length);
});
// Remove excess slices
newSlices.exit().remove();
// Add a title
var title = svg.append("text")
.attr("x", 0)
.attr("y", -(outerRadius + 10))
.style("text-anchor", "middle")
.text("Distrubution of " + name + " Usage");
// Add labels
var labels = svg.selectAll(null)
.data(newData)
.enter()
.append("text")
.attr("fill", "white")
.attr("id", function (d, i) { return i })
.attr("transform", function (d) {
d.innerRadius = 0;
d.outerRadius = outerRadius;
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function (d, i) {
return dataSet[i]["label"];
});
// Add tooltips
svg.selectAll("path").data(newData).append("title").text(function (d) { return d["value"] + " hits"; });
svg.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", innerRadius)
.style("fill", "white")
.style("cursor", "pointer")
.on("click", function () {
changeToAPI("Controller", dataController);
});
// Adds back button if not at controller level
if (dataSet !== dataController) {
svg.append("text")
.attr("x", 0)
.attr("y", 12)
.style("text-anchor", "middle")
.style("color", "#efefef")
.style("font-size", "40px")
.text("Back");
}
}
}
function changeTo(name, dataSet) {
// Don't update if the data is already showing
// JavaScript doesn't short circuit?
if (dataSet === null) {
dataSet = [{ "label": "No data...", "value": 1 }];
} else if (dataSet.length === 0) {
dataSet = [{ "label": "No data...", "value": 1 }];
}
mode = name;
// Get the new pie and color functions
var newData = pie(dataSet);
var newColor = getColor(name);
// Remove the labels, titles, and tooltips
svg.selectAll("text").remove();
svg.selectAll("title").remove();
// Line below fixes an error that doesn't cause issues, but makes the graph ugly :(
//svg.selectAll("a").remove();
// Add the new slices if there are any
var newSlices = svg.selectAll("a")
.data(newData);
newSlices.enter()
.append("a")
.append("path")
.style("cursor", "pointer");
// Update the attributes of those slices and animate the transition
newSlices.select("path")
.each(function (d) { d.outerRadius = outerRadius - 20; })
.transition()
.attr("fill", function (d, i) { return newColor(i); })
.attr("d", arc)
.attr("title", function (d) { return d["value"]; });
newSlices.selectAll("path")
.on("mouseover.arc", arcTween(outerRadius, 0))
.on("mouseover.text", function (d, i) {
visibilityHide(i, dataSet.length);
})
.on("mouseout.arc", arcTween(outerRadius - 20, 150))
.on("mouseout.text", function (d, i) {
visibilityShow(dataSet.length);
});
// Remove excess slices
newSlices.exit().remove();
// Add a title
svg.append("text")
.attr("x", 0)
.attr("y", -(outerRadius + 10))
.style("text-anchor", "middle")
.text(function (e) {
var title = "Distrubution of " + name + " Usage";
if (name === "Defualt") {
title = "Loading..."
}
return title;
});
// Add labels
svg.selectAll(null)
.data(newData)
.enter()
.append("text")
.attr("fill", "white")
.attr("id", function (d, i) { return i })
.attr("transform", function (d) {
d.innerRadius = 0;
d.outerRadius = outerRadius;
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function (d, i) {
return dataSet[i]["label"];
});
// Add tooltips
svg.selectAll("path").data(newData).append("title").text(function (d) { return d["value"] + " hits"; });
}
function checkForChild(name, dataSet) {
if (dataSet.hasOwnProperty("child")) {
if (dataSet["child"] !== null) {
if (dataSet["child"].length !== 0) {
changeToAPI(name, dataSet["child"]);
}
}
}
}
// Hashcode generator for strings
function hashify(string) {
var hash = 0;
// Add the value of each char to the hash value
for (var i = 0; i < string.length; i++) {
hash += string.charCodeAt(i);
}
return hash;
}
function visibilityShow(dataSetSize) {
for (var i = 0; i < dataSetSize; i++) {
$("#" + i).show();
}
}
function visibilityHide(index, dataSetSize) {
for (var i = 0; i < dataSetSize; i++) {
if (i === index) {
$("#" + i).show();
} else {
$("#" + i).hide();
}
}
}
body {
font-family: Arial;
transition: all ease .5s;
text-align: center;
color: rgb(58,58,58);
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>General Statistics</title>
</head>
<body>
<div id="graphs">
</div>
</body>
</html>
This simple css should do it:
#text:hover {
color: transparent;
}
Using D3.js's force layout I'm trying to make the links automatically generate based on the node data. The nodes already appear exactly as expected.
The database json strings use the following format:
{
"id": 1,
"title": "name"
},
{
"id": 2,
"title": "other name",
"primaryDependants": 1
}
and I'm basically trying to have it say:
'for each node, check if it has a primaryDependant property, if it does then make a link between that node and the one identified as the primary dependant.'
however I haven't dealt with force graphs before and tutorials are few and far between so I'm really struggling with how to make any change to my code without breaking it. Currently it is based on the answer here and I use the Meteor framework if that's of any relevance.
Template.tree.rendered = function () {
var graph = new myGraph("#svgdiv");
Lessons.find().observe({
added: function (doc) {
graph.addNode(doc._id, doc.title);
},
removed: function (doc) {
graph.removeNode(doc._id);
}
});
function myGraph(el) {
w = 1500,
h = 1000;
var svg = d3.select(el)
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("pointer-events", "all")
svg.append("rect")
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "lightgrey");
var vis = svg.append('g');
var force2 = d3.layout.force();
var links = force2.links();
var nodes = force2.nodes();
var update = function () {
var link = vis.selectAll("line")
.data(links, function(d) {return d.source.id + "-" + d.target.id;});
link.enter().append("line")
.attr("id",function(d){return d.source.id + "-" + d.target.id;})
.attr("class","link");
link.append("title")
.text(function(d){
return d.value;
});
link.exit().remove();
var node = vis.selectAll("g")
.data(nodes, function(d) { return d.id;});
var nodeEnter = node.enter()
.append("g")
.call(force2.drag)
.append("circle")
.attr("r", 8)
.attr("fill", "#585858")
.attr("stroke", "#008db7")
.attr("stroke-width", 3)
.attr("id", function(e) { return "Node;"+e.id;})
.attr("class", ( function(f){return f.id;}));
node.exit().remove();
force2.on("tick", function() {
node.attr("transform", function(g) { return "translate(" + g.x + "," + g.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; });
});
force2
.gravity(.02)
.linkDistance( 200 )
.size([w, h])
.start();
};
update();
var findNode = function(id) {
for (var i in nodes) {
if (nodes[i]["id"] === id) return nodes[i];};
};
var findNodeIndex = function(id) {
for (var i=0;i<nodes.length;i++) {
if (nodes[i].id==id){
return i;
}
};
};
this.addNode = function (id, title) {
nodes.push({"id":id,"title":title});
update();
};
this.addLink = function (source, target, value) {
links.push({"source":findNode(source),"target":findNode(target),"value":value});
update();
};
this.removeNode = function (id) {
var i = 0;
var n = findNode(id);
nodes.splice(findNodeIndex(id),1);
update();
};
}
To create the links array based on your description:
var dataset = [{
"id": 1,
"title": "name"
},
{
"id": 2,
"title": "other name",
"primaryDependants": 1
}];
var links = [];
dataset.forEach(function(d){
if(d.primaryDependants){
links.push({source: d.id,
target: d.primaryDependants});
}});
console.log(links)
Have been struggling for ages to create a horizontal tree layout with rectangles instead of circles, and have the text wrap inside those rectangles. Nothing I do seems to work, I have tried this code but whoever made it has left out a crucial step, in defining the variable d before the line
if (d.name.length > 26) which stops the whole script from running.
I have also been trying to use d3plus.js from http://d3plus.org/ in order to wrap text inside rect tags but it actually doesn't work half the time and seems to need a trigger like a click function in order to work. Also considering using this example as a guide on text wrapping.
In my research I have not found that anybody has done the combination of horizontal, rectangles and wrapped text in one diagram.
Also I am a bit of a d3 noob so all help is appreciated.
Here is a JSFiddle.
Here is the current code I am using which isn't working:
var w = 960,
h = 2000,
i = 0,
duration = 500,
root;
var tree = d3.layout.tree()
.size([h, w - 160]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
var vis = d3.select("#container").append("svg:svg")
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("transform", "translate(40,0)");
root = treeData[0];
root.x0 = h / 2;
root.y0 = 0;
update(root);
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse();
// Update the nodes…
var node = vis.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
var nodeEnter = node.enter().append("svg:g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; });
// Enter any new nodes at the parent's previous position.
nodeEnter.append("svg:rect")
.attr("width", 150)
.attr("height", function(d) { return (d.name.length > 30) ? 38 : 19;})
.attr("y",-11)
.attr("rx",2)
.attr("ry",2)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; })
.on("click", click);
if (d.name.length > 26) {
nodeEnter.append("svg:text")
.attr("x", function(d) { return d._children ? -8 : 8; })
.attr("y", 3)
.text(function(d) { return d.name; });
} else {
nodeEnter.append("svg:text")
.attr("x", function(d) { return d._children ? -8 : 8; })
.attr("y", 3)
.append("svg:tspan")
.text(function(d) { return d.name.slice(0,26); })
.append("svg:tspan")
.attr("x", function(d) { return d._children ? -8 : 8; })
.attr("y",15)
.text(function(d) { return d.name.slice(26); });
}
}
// Transition nodes to their new position.
nodeEnter.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
.style("opacity", 1)
.select("rect")
.style("fill", "lightsteelblue");
node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
.style("opacity", 1);
node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.style("opacity", 1e-6)
.remove();
// Update the links…
var link = vis.selectAll("path.link")
.data(tree.links(nodes), function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("svg:path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
})
.transition()
.duration(duration)
.attr("d", diagonal);
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
d3.select(self.frameElement).style("height", "2000px");
As well as my json:
var treeData = [
{
"name": "Do trainees require direction as to what to do or how to do the task (either before they start or while they are completing it?",
"children": [
{
"name": "Can they satisfactorily complete the task assigned to them?",
"children": [
{
"name": "Rating level 4",
"parent": "A",
},
{
"name": "How many problems / queries are there that still need to be addressed / resolved to be able to satisfactorily complete the task?",
"children": [
{
"name": "Are problems / queries fundamental to the completion of the task at hand?",
"children": [
{
"name": "Rating level 4",
},
{
"name": "Can the problems be resolved by the trainee (after receiving guidance)?",
"children": [
{
"name": "Rating level 3",
},
{
"name": "Can the problems be resolved by the trainee (after receiving guidance)?",
"children": [
{
"name": "Rating level 2",
},
{
"name": "Rating level 1",
}
]
}
]
}
]
},
{
"name": "Are problems / queries fundamental to the completion of the task at hand?",
}
]
}
]
},
{
"name": "Can they satisfactorily complete the task assigned to them?",
"children": [
{
"name": "Rating 1",
},
{
"name": "Rating 2",
},
{
"name": "Rating 3",
},
{
"name": "Rating 4",
}
]
}
]
}];
Your code throws an error at this line:
if (d.name.length > 26) {
d isn't defined. When d3 code references d, it's usually in the scope of a data binding. At this place in the code, you are not looping a binding, like:
nodeEnter.append("text")
.attr("x", function(d) {
return d._children ? -8 : 8;
})
.attr("y", 3)
.attr("dy", "0em")
.text(function(d) {
return d.name; // d is defined from the binding
});
That said, I like the wrap function you link to. So add your text like above and then wrap the text:
wrap(d3.selectAll('text'),150);
Here's a quick modification to the wrap that'll resize your rects as well:
function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
// find corresponding rect and reszie
d3.select(this.parentNode.children[0]).attr('height', 19 * (lineNumber+1));
});
}
Example here.