I am new to d3.js and coding in general. This is my question:
I am trying to find a way to break long displayed names of force layout objects in lines.
I would like to be able to determine where to break these lines, and I am guessing this is something that might be possible to be done from the json file.
I am aware that there have been similar questions asked already, but I just can't find where to put the code or why my previous attempts haven't been successful. This is the code that I have:
var width = 960,
height = 800,
root;
var force = d3.layout.force()
.linkDistance(120)
.charge(-600)
.gravity(.06)
.size([width, height])
.on("tick", tick);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var link = svg.selectAll(".link"),
node = svg.selectAll(".node");
d3.json("graph.json", function(error, json) {
root = json;
update();
});
function update() {
var nodes = flatten(root),
links = d3.layout.tree().links(nodes);
// Restart the force layout.
force
.nodes(nodes)
.links(links)
.start();
// Update links.
link = link.data(links, function(d) { return d.target.id; });
link.exit().remove();
link.enter().insert("line", ".node")
.attr("class", "link");
// Update nodes.
node = node.data(nodes, function(d) { return d.id; });
node.exit().remove();
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.on("click", click)
.call(force.drag);
nodeEnter.append("circle")
.attr("r", function(d) { return Math.sqrt(d.size) / 3 || 10; });
nodeEnter.append("text")
.attr("dy", "0.3em")
.text(function(d) { return d.name; });
node.select("circle")
.style("fill", color);
}
// Divide text
text.append("text")
.each(function (d) {
var arr = d.name.split(" ");
if (arr != undefined) {
for (i = 0; i < arr.length; i++) {
d3.select(this).append("tspan")
.text(arr[i])
.attr("dy", i ? "1.2em" : 0)
.attr("x", 0)
.attr("text-anchor", "middle")
.attr("class", "tspan" + i);
}
}
});
// Divide text
function tick() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}
function color(d) {
return d._children ? "#9ecae1" // collapsed package
: d.children ? "#ffffff" // expanded package
: "#ffcc50"; // leaf node
}
// Toggle children on click.
function click(d) {
if (d3.event.defaultPrevented) return; // ignore drag
if (d.children) {
d._children = d.children;
d.children = null;
} else if (d._children) {
d.children = d._children;
d._children = null;
} else {
// This was a leaf node, so redirect.
window.open(d.url, 'popUpWindow','height=600,width=800,left=10,top=10,resizable=yes,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=yes');
}
update();
}
// Returns a list of all nodes under the root.
function flatten(root) {
var nodes = [], i = 0;
function recurse(node) {
if (node.children) node.children.forEach(recurse);
if (!node.id) node.id = ++i;
nodes.push(node);
}
recurse(root);
return nodes;
}
And this is the json info:
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{"name": "Agglomerative Cluster", "size": 3938},
{"name": "Community Structure", "size": 3812},
{"name": "Hierarchical Cluster", "size": 6714},
{"name": "Merge Edge", "size": 743}
]
},
{
"name": "graph",
"children": [
{"name": "Betweenness Centrality", "size": 3534},
{"name": "Link Distance", "size": 5731},
{"name": "Max Flow Min Cut", "size": 7840},
{"name": "Shortest Paths", "size": 5914},
{"name": "Spanning Tree", "size": 3416}
]
},
{
"name": "optimization",
"children": [
{"name": "Aspect Ratio Banker", "size": 7074}
]
}
]
}
]
I would like to be able to decide, for example, to break Aspect / Ratio Banker or Aspect Ratio / Banker.
I am new to d3.js and coding in general. This is my question:
I am trying to find a way to break long displayed names of force layout objects in lines.
I would like to be able to determine where to break these lines, and I am guessing this is something that might be possible to be done from the json file.
I am aware that there have been similar questions asked already, but I just can't find where to put the code or why my previous attempts haven't been successful. This is the code that I have:
var width = 960,
height = 800,
root;
var force = d3.layout.force()
.linkDistance(120)
.charge(-600)
.gravity(.06)
.size([width, height])
.on("tick", tick);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var link = svg.selectAll(".link"),
node = svg.selectAll(".node");
d3.json("graph.json", function(error, json) {
root = json;
update();
});
function update() {
var nodes = flatten(root),
links = d3.layout.tree().links(nodes);
// Restart the force layout.
force
.nodes(nodes)
.links(links)
.start();
// Update links.
link = link.data(links, function(d) { return d.target.id; });
link.exit().remove();
link.enter().insert("line", ".node")
.attr("class", "link");
// Update nodes.
node = node.data(nodes, function(d) { return d.id; });
node.exit().remove();
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.on("click", click)
.call(force.drag);
nodeEnter.append("circle")
.attr("r", function(d) { return Math.sqrt(d.size) / 3 || 10; });
nodeEnter.append("text")
.attr("dy", "0.3em")
.text(function(d) { return d.name; });
node.select("circle")
.style("fill", color);
}
// Divide text
text.append("text")
.each(function (d) {
var arr = d.name.split(" ");
if (arr != undefined) {
for (i = 0; i < arr.length; i++) {
d3.select(this).append("tspan")
.text(arr[i])
.attr("dy", i ? "1.2em" : 0)
.attr("x", 0)
.attr("text-anchor", "middle")
.attr("class", "tspan" + i);
}
}
});
// Divide text
function tick() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}
function color(d) {
return d._children ? "#9ecae1" // collapsed package
: d.children ? "#ffffff" // expanded package
: "#ffcc50"; // leaf node
}
// Toggle children on click.
function click(d) {
if (d3.event.defaultPrevented) return; // ignore drag
if (d.children) {
d._children = d.children;
d.children = null;
} else if (d._children) {
d.children = d._children;
d._children = null;
} else {
// This was a leaf node, so redirect.
window.open(d.url, 'popUpWindow','height=600,width=800,left=10,top=10,resizable=yes,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=yes');
}
update();
}
// Returns a list of all nodes under the root.
function flatten(root) {
var nodes = [], i = 0;
function recurse(node) {
if (node.children) node.children.forEach(recurse);
if (!node.id) node.id = ++i;
nodes.push(node);
}
recurse(root);
return nodes;
}
And this is the json info:
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{"name": "Agglomerative Cluster", "size": 3938},
{"name": "Community Structure", "size": 3812},
{"name": "Hierarchical Cluster", "size": 6714},
{"name": "Merge Edge", "size": 743}
]
},
{
"name": "graph",
"children": [
{"name": "Betweenness Centrality", "size": 3534},
{"name": "Link Distance", "size": 5731},
{"name": "Max Flow Min Cut", "size": 7840},
{"name": "Shortest Paths", "size": 5914},
{"name": "Spanning Tree", "size": 3416}
]
},
{
"name": "optimization",
"children": [
{"name": "Aspect Ratio Banker", "size": 7074}
]
}
]
}
]
I would like to be able to decide, for example, to break Aspect / Ratio Banker or Aspect Ratio / Banker.
Share Improve this question edited Jan 15, 2015 at 15:33 VividD 10.5k8 gold badges66 silver badges112 bronze badges asked Dec 28, 2013 at 3:21 ErnestoErnesto 1992 silver badges9 bronze badges 4- You have to insert the line breaks yourself. See for example this question. – Lars Kotthoff Commented Dec 28, 2013 at 8:26
- @ViviD, one question, I noted that the following portion of code: nodeEnter.append("text") .attr("dy", "0.3em") ... might be affecting the position of the text in relation with the circles, Is there a way to place the first line closely to the center in a relatively easy way? – Ernesto Commented Dec 29, 2013 at 23:51
- Experiment with dy, thats it. Also, you can center the text horizontally, see svg documentation. – VividD Commented Dec 30, 2013 at 8:36
- You can play with dx too. If you set dx to be radius of the circle, the whole text will appear outside of the circle, just beside it. – VividD Commented Jan 1, 2014 at 11:45
1 Answer
Reset to default 8I believe this example on jsfiddle solves your problem.
The code is actually your example, just a little bit modified.
There is a new function wordwrap2() that takes care of proper splitting of the names:
function wordwrap2( str, width, brk, cut ) {
brk = brk || '\n';
width = width || 75;
cut = cut || false;
if (!str) { return str; }
var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
return str.match( RegExp(regex, 'g') ).join( brk );
}
Then, there is a new important part of the code that, instead of just creating one text label per node, creates this:
var maxLength = 20;
var separation = 18;
var textX = 0;
nodeEnter.append("text")
.attr("dy", "0.3em")
.each(function (d) {
var lines = wordwrap2(d.name, maxLength).split('\n');
console.log(d.name);
console.log(lines);
for (var i = 0; i < lines.length; i++) {
d3.select(this)
.append("tspan")
.attr("dy", separation)
.attr("x", textX)
.text(lines[i]);
}
});
(variable maxLength - length used for criterium for splitting names)
(variable separation - visual vertical distance between split lines of a name)
For example this would be the output for maxLength=20:
This would be the output for maxLength=15: (notice that Aspect Ratio Banker became Aspect Ratio/Banker)
This would be the output for maxLength=10: (now, check out Aspect/Ratio/Banker !)
And this would be the output for maxLength=10 and separation=30 (a little more space between individual lines):
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745108466a4611700.html
评论列表(0条)