I am trying to add some text into circle. I have been following example from a mbostock tutorial, but wasn't able to get the right output.
The code snippet is:
var data;
var code;
d3.json("/json/trace.json", function(json) {
data = json;
console.log(data);
// get code for visualization
code = data["code"];
alert(code);
var mainSVG = d3
.select("#viz")
.append("svg")
.attr("width", 900)
.attr("height", 900);
mainSVG
.append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", 100)
.attr("cx", 300)
.attr("cy", 300);
circle = mainSVG.selectAll("circle").data([code]);
});
Any suggestions how to get this work?
Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:
The main idea behind this is to encapsulate the text and the circle in the same "div" as you would do in html to have the logo and the name of the company in the same div in a page header.
The main code is:
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
d3.json("data.json", function(json) {
/* Define the data for the circles */
var elem = svg.selectAll("g")
.data(json.nodes)
/*Create and place the "blocks" containing the circle and the text */
var elemEnter = elem.enter()
.append("g")
.attr("transform", function(d){return "translate("+d.x+",80)"})
/*Create the circle for each block */
var circle = elemEnter.append("circle")
.attr("r", function(d){return d.r} )
.attr("stroke","black")
.attr("fill", "white")
/* Create the text for each block */
elemEnter.append("text")
.attr("dx", function(d){return -20})
.text(function(d){return d.label})
})
and the json file is:
{"nodes":[
{"x":80, "r":40, "label":"Node 1"},
{"x":200, "r":60, "label":"Node 2"},
{"x":380, "r":80, "label":"Node 3"}
]}
The resulting html code shows the encapsulation you want:
<svg width="960" height="500">
<g transform="translate(80,80)">
<circle r="40" stroke="black" fill="white"></circle>
<text dx="-20">Node 1</text>
</g>
<g transform="translate(200,80)">
<circle r="60" stroke="black" fill="white"></circle>
<text dx="-20">Node 2</text>
</g>
<g transform="translate(380,80)">
<circle r="80" stroke="black" fill="white"></circle>
<text dx="-20">Node 3</text>
</g>
</svg>
jsfiddle with working code: http://jsfiddle.net/chrisJamesC/DY7r4/
Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.
var width = 960,
height = 500,
json = {
"nodes": [{
"x": 100,
"r": 20,
"label": "Node 1",
"color": "red"
}, {
"x": 200,
"r": 25,
"label": "Node 2",
"color": "blue"
}, {
"x": 300,
"r": 30,
"label": "Node 3",
"color": "green"
}]
};
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
svg.append("defs")
.append("pattern")
.attr({
"id": "stripes",
"width": "8",
"height": "8",
"fill": "red",
"patternUnits": "userSpaceOnUse",
"patternTransform": "rotate(60)"
})
.append("rect")
.attr({
"width": "4",
"height": "8",
"transform": "translate(0,0)",
"fill": "grey"
});
function plotChart(json) {
/* Define the data for the circles */
var elem = svg.selectAll("g myCircleText")
.data(json.nodes)
/*Create and place the "blocks" containing the circle and the text */
var elemEnter = elem.enter()
.append("g")
.attr("class", "node-group")
.attr("transform", function(d) {
return "translate(" + d.x + ",80)"
})
/*Create the circle for each block */
var circleInner = elemEnter.append("circle")
.attr("r", function(d) {
return d.r
})
.attr("stroke", function(d) {
return d.color;
})
.attr("fill", function(d) {
return d.color;
});
var circleOuter = elemEnter.append("circle")
.attr("r", function(d) {
return d.r
})
.attr("stroke", function(d) {
return d.color;
})
.attr("fill", "url(#stripes)");
/* Create the text for each block */
elemEnter.append("text")
.text(function(d) {
return d.label
})
.attr({
"text-anchor": "middle",
"font-size": function(d) {
return d.r / ((d.r * 10) / 100);
},
"dy": function(d) {
return d.r / ((d.r * 25) / 100);
}
});
};
plotChart(json);
.node-group {
fill: #ffffff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Output:
Below is the link to codepen also:
See the Pen D3-Circle-Pattern-Text by Manish Kumar (#mkdudeja) on CodePen.
Thanks,
Manish Kumar
Here's a way that I consider easier:
The general idea is that you want to append a text element to a circle element then play around with its "dx" and "dy" attributes until you position the text at the point in the circle that you like. In my example, I used a negative number for the dx since I wanted to have text start towards the left of the centre.
const nodes = [ {id: ABC, group: 1, level: 1}, {id:XYZ, group: 2, level: 1}, ]
const nodeElems = svg.append('g')
.selectAll('circle')
.data(nodes)
.enter().append('circle')
.attr('r',radius)
.attr('fill', getNodeColor)
const textElems = svg.append('g')
.selectAll('text')
.data(nodes)
.enter().append('text')
.text(node => node.label)
.attr('font-size',8)//font size
.attr('dx', -10)//positions text towards the left of the center of the circle
.attr('dy',4)
Related
I've got a simple function that supposed to display a couple of text elements.
function d3manipulation() {
var svg = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 500);
var nodes = [
{ "name": "Michael" },
{ "name": "John" }
];
svg
.selectAll("text")
.data(nodes)
.enter()
.append("text")
.text(function(d) { return d.name; });
}
But on the page it shows nothing. I don't have any console errors either.
However inspector shows that there are in fact text elements with the data.
<svg width="500" height="500">
<text>Michael</text>
<text>John</text>
</svg>
What is the problem?
Giving it an x and y was enough like #jrook suggested. (default fill is black)
var svg = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 500);
var nodes = [
{ "name": "Michael" },
{ "name": "John" }
];
svg
.selectAll("text")
.data(nodes)
.enter()
.append("text")
.text(function(d) { return d.name; })
.attr('x', 20)
.attr('y', (d, i) => 30 + 20 * i);
<script src="https://d3js.org/d3.v5.min.js"></script>
I've been using the sample code from this d3 project to learn how to display d3 graphs and I can't seem to get text to show up in the middle of the circles (similar to this example and this example). I've looked at other examples and have tried adding
node.append("title").text("Node Name To Display")
and
node.append("text")
.attr("text-anchor", "middle")
.attr("dy", ".3em").text("Node Name To Display")
right after node is defined but the only results I see is "Node Name To Display" is showing up when I hover over each node. It's not showing up as text inside the circle. Do I have to write my own svg text object and determine the coordinates of that it needs to be placed at based on the coordinates of radius of the circle? From the other two examples, it would seem like d3 already takes cares of this somehow. I just don't know the right attribute to call/set.
There are lots of examples showing how to add labels to graph and tree visualizations, but I'd probably start with this one as the simplest:
http://bl.ocks.org/950642
You haven’t posted a link to your code, but I'm guessing that node refers to a selection of SVG circle elements. You can’t add text elements to circle elements because circle elements are not containers; adding a text element to a circle will be ignored.
Typically you use a G element to group a circle element (or an image element, as above) and a text element for each node. The resulting structure looks like this:
<g class="node" transform="translate(130,492)">
<circle r="4.5"/>
<text dx="12" dy=".35em">Gavroche</text>
</g>
Use a data-join to create the G elements for each node, and then use selection.append to add a circle and a text element for each. Something like this:
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("r", 4.5);
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name });
One downside of this approach is that you may want the labels to be drawn on top of the circles. Since SVG does not yet support z-index, elements are drawn in document order; so, the above approach causes a label to be drawn above its circle, but it may be drawn under other circles. You can fix this by using two data-joins and creating separate groups for circles and labels, like so:
<g class="nodes">
<circle transform="translate(130,492)" r="4.5"/>
<circle transform="translate(110,249)" r="4.5"/>
…
</g>
<g class="labels">
<text transform="translate(130,492)" dx="12" dy=".35em">Gavroche</text>
<text transform="translate(110,249)" dx="12" dy=".35em">Valjean</text>
…
</g>
And the corresponding JavaScript:
var circle = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("r", 4.5)
.call(force.drag);
var text = svg.append("g")
.attr("class", "labels")
.selectAll("text")
.data(nodes)
.enter().append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name });
This technique is used in the Mobile Patent Suits example (with an additional text element used to create a white shadow).
I found this guide very useful in trying to accomplish something similar :
https://www.dashingd3js.com/svg-text-element
Based on above link this code will generate circle labels :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body style="overflow: hidden;">
<div id="canvas" style="overflow: hidden;"></div>
<script type="text/javascript">
var graph = {
"nodes": [
{name: "1", "group": 1, x: 100, y: 90, r: 10 , connected : "2"},
{name: "2", "group": 1, x: 200, y: 50, r: 15, connected : "1"},
{name: "3", "group": 2, x: 200, y: 130, r: 25, connected : "1"}
]
}
$( document ).ready(function() {
var width = 2000;
var height = 2000;
var svg = d3.select("#canvas").append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
var lines = svg.attr("class", "line")
.selectAll("line").data(graph.nodes)
.enter().append("line")
.style("stroke", "gray") // <<<<< Add a color
.attr("x1", function (d, i) {
return d.x
})
.attr("y1", function (d) {
return d.y
})
.attr("x2", function (d) {
return findAttribute(d.connected).x
})
.attr("y2", function (d) {
return findAttribute(d.connected).y
})
var circles = svg.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", function (d, i) {
return d.r
})
.attr("cx", function (d, i) {
return d.x
})
.attr("cy", function (d, i) {
return d.y
});
var text = svg.selectAll("text")
.data(graph.nodes)
.enter()
.append("text");
var textLabels = text
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; })
.text( function (d) { return d.name })
.attr("font-family", "sans-serif")
.attr("font-size", "10px")
.attr("fill", "red");
});
function findAttribute(name) {
for (var i = 0, len = graph.nodes.length; i < len; i++) {
if (graph.nodes[i].name === name)
return graph.nodes[i]; // Return as soon as the object is found
}
return null; // The object was not found
}
</script>
</body>
</html>
If you want to grow the nodes to fit large labels, you can use the getBBox property of an SVG text node after you've drawn it. Here's how I did it, for a list of nodes with fixed coordinates, and two possible shapes:
nodes.forEach(function(v) {
var nd;
var cx = v.coord[0];
var cy = v.coord[1];
switch (v.shape) {
case "circle":
nd = svg.append("circle");
break;
case "rectangle":
nd = svg.append("rect");
break;
}
var w = 10;
var h = 10;
if (v.label != "") {
var lText = svg.append("text");
lText.attr("x", cx)
.attr("y", cy + 5)
.attr("class", "labelText")
.text(v.label);
var bbox = lText.node().getBBox();
w = Math.max(w,bbox.width);
h = Math.max(h,bbox.height);
}
var pad = 4;
switch (v.shape) {
case "circle":
nd.attr("cx", cx)
.attr("cy", cy)
.attr("r", Math.sqrt(w*w + h*h)/2 + pad);
break;
case "rectangle":
nd.attr("x", cx - w/2 - pad)
.attr("y", cy - h/2 - pad)
.attr("width", w + 2*pad)
.attr("height", h + 2*pad);
break;
}
});
Note that the shape is added, the text is added, then the shape is positioned, in order to get the text to show on top.
I've been using the sample code from this d3 project to learn how to display d3 graphs and I can't seem to get text to show up in the middle of the circles (similar to this example and this example). I've looked at other examples and have tried adding
node.append("title").text("Node Name To Display")
and
node.append("text")
.attr("text-anchor", "middle")
.attr("dy", ".3em").text("Node Name To Display")
right after node is defined but the only results I see is "Node Name To Display" is showing up when I hover over each node. It's not showing up as text inside the circle. Do I have to write my own svg text object and determine the coordinates of that it needs to be placed at based on the coordinates of radius of the circle? From the other two examples, it would seem like d3 already takes cares of this somehow. I just don't know the right attribute to call/set.
There are lots of examples showing how to add labels to graph and tree visualizations, but I'd probably start with this one as the simplest:
http://bl.ocks.org/950642
You haven’t posted a link to your code, but I'm guessing that node refers to a selection of SVG circle elements. You can’t add text elements to circle elements because circle elements are not containers; adding a text element to a circle will be ignored.
Typically you use a G element to group a circle element (or an image element, as above) and a text element for each node. The resulting structure looks like this:
<g class="node" transform="translate(130,492)">
<circle r="4.5"/>
<text dx="12" dy=".35em">Gavroche</text>
</g>
Use a data-join to create the G elements for each node, and then use selection.append to add a circle and a text element for each. Something like this:
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("r", 4.5);
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name });
One downside of this approach is that you may want the labels to be drawn on top of the circles. Since SVG does not yet support z-index, elements are drawn in document order; so, the above approach causes a label to be drawn above its circle, but it may be drawn under other circles. You can fix this by using two data-joins and creating separate groups for circles and labels, like so:
<g class="nodes">
<circle transform="translate(130,492)" r="4.5"/>
<circle transform="translate(110,249)" r="4.5"/>
…
</g>
<g class="labels">
<text transform="translate(130,492)" dx="12" dy=".35em">Gavroche</text>
<text transform="translate(110,249)" dx="12" dy=".35em">Valjean</text>
…
</g>
And the corresponding JavaScript:
var circle = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("r", 4.5)
.call(force.drag);
var text = svg.append("g")
.attr("class", "labels")
.selectAll("text")
.data(nodes)
.enter().append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name });
This technique is used in the Mobile Patent Suits example (with an additional text element used to create a white shadow).
I found this guide very useful in trying to accomplish something similar :
https://www.dashingd3js.com/svg-text-element
Based on above link this code will generate circle labels :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body style="overflow: hidden;">
<div id="canvas" style="overflow: hidden;"></div>
<script type="text/javascript">
var graph = {
"nodes": [
{name: "1", "group": 1, x: 100, y: 90, r: 10 , connected : "2"},
{name: "2", "group": 1, x: 200, y: 50, r: 15, connected : "1"},
{name: "3", "group": 2, x: 200, y: 130, r: 25, connected : "1"}
]
}
$( document ).ready(function() {
var width = 2000;
var height = 2000;
var svg = d3.select("#canvas").append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
var lines = svg.attr("class", "line")
.selectAll("line").data(graph.nodes)
.enter().append("line")
.style("stroke", "gray") // <<<<< Add a color
.attr("x1", function (d, i) {
return d.x
})
.attr("y1", function (d) {
return d.y
})
.attr("x2", function (d) {
return findAttribute(d.connected).x
})
.attr("y2", function (d) {
return findAttribute(d.connected).y
})
var circles = svg.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", function (d, i) {
return d.r
})
.attr("cx", function (d, i) {
return d.x
})
.attr("cy", function (d, i) {
return d.y
});
var text = svg.selectAll("text")
.data(graph.nodes)
.enter()
.append("text");
var textLabels = text
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; })
.text( function (d) { return d.name })
.attr("font-family", "sans-serif")
.attr("font-size", "10px")
.attr("fill", "red");
});
function findAttribute(name) {
for (var i = 0, len = graph.nodes.length; i < len; i++) {
if (graph.nodes[i].name === name)
return graph.nodes[i]; // Return as soon as the object is found
}
return null; // The object was not found
}
</script>
</body>
</html>
If you want to grow the nodes to fit large labels, you can use the getBBox property of an SVG text node after you've drawn it. Here's how I did it, for a list of nodes with fixed coordinates, and two possible shapes:
nodes.forEach(function(v) {
var nd;
var cx = v.coord[0];
var cy = v.coord[1];
switch (v.shape) {
case "circle":
nd = svg.append("circle");
break;
case "rectangle":
nd = svg.append("rect");
break;
}
var w = 10;
var h = 10;
if (v.label != "") {
var lText = svg.append("text");
lText.attr("x", cx)
.attr("y", cy + 5)
.attr("class", "labelText")
.text(v.label);
var bbox = lText.node().getBBox();
w = Math.max(w,bbox.width);
h = Math.max(h,bbox.height);
}
var pad = 4;
switch (v.shape) {
case "circle":
nd.attr("cx", cx)
.attr("cy", cy)
.attr("r", Math.sqrt(w*w + h*h)/2 + pad);
break;
case "rectangle":
nd.attr("x", cx - w/2 - pad)
.attr("y", cy - h/2 - pad)
.attr("width", w + 2*pad)
.attr("height", h + 2*pad);
break;
}
});
Note that the shape is added, the text is added, then the shape is positioned, in order to get the text to show on top.
I've got a pie chart and it will only draw once. I got it from Mike Bostock's pie chart example. I'm new to D3 and I can't figure out why it won't redraw. I saw this post about redrawing a bar chart, but for some reason that technique doesn't work on my pie chart. I'm sure I'm doing something wrong.
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.percent; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
function drawChart(error, data) {
console.log("here");
data.forEach(function(d) {
d.percent = +d.percent;
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) {
console.log("inside path");
return d.data.color;
});
g.append("text")
.attr("transform", function(d) { console.log("inside transform", d);return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.color; });
}
drawChart(undefined, [{"color": "green", "percent": 50}, {"color": "red", "percent": 50}]);
setTimeout(function () {
drawChart(undefined, [{"color": "green", "percent": 75}, {"color": "red", "percent": 25}]);
}, 1000)
here's the jsbin.
Problem 1:
You are adding the d attribute to the DOM g which is wrong.
<g class="arc" d="M-240,2.939152317953648e-14A240,240 0 0,1 -4.408728476930471e-14,-240L0,0Z">
<path d="M-9.188564877424678e-14,240A240,240 0 1,1 1.6907553595872533e-13,-240L0,0Z" style="fill: red;">
</path>
<text transform="translate(-120,-9.188564877424678e-14)" dy=".35em" style="text-anchor: middle;">red</text>
</g>
d attribute is only for path not for g.
So this line is incorrect
g.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
Problem 2:
Your update function is incorrect(same reason problem 1)
function update (data) {
console.log("here", data);
var value = this.value;
g = g.data(pie(data)); // compute the new angles
g.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
};
In my opinion you should call your drawChart function again for update.
with an exception that you remove old g group like this.
svg.selectAll(".arc").remove();
The advantage is that we are using the same code for create and update (DRY).
So your timeout function becomes like thsi
setTimeout(function () {
drawChart(undefined, [{"color": "green", "percent": 75}, {"color": "red", "percent": 25}]);
}, 2000);
Full working code here
Hope this helps!
Here is the code:
//Circle Data Set
var circleData = [
{ "cx": 20, "cy": 20, "radius": 20, "color" : "green" },
{ "cx": 70, "cy": 70, "radius": 20, "color" : "purple" }];
//Create the SVG Viewport
var svgContainer = d3.select("#svgContainer")
.attr("width",200)
.attr("height",200);
//Add the SVG Text Element to the svgContainer
var text = svgContainer.selectAll("text")
.data(circleData)
.enter()
.append("text");
var circles = svgContainer.selectAll("circle")
.data(circleData)
.enter()
.append("circle")
.attr("cx", function(d) {return d.cx})
.attr("cy", function(d) {return d.cy})
.attr("r", function(d) {return d.radius})
.attr("fill", function(d) {return d.color})
//Add SVG Text Element Attributes
var textLabels = text
.attr("x", function(d) { return d.cx; })
.attr("y", function(d) { return d.cy; })
.text( function (d) { return "( " + d.cx + ", " + d.cy +" )"; })
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");
http://jsfiddle.net/kindlychung/jrsxLfpg/1/
It seems d3 always renders text first, which means the text is partly hidden behind the circles:
<svg id="svgContainer" width="200" height="200">
<text x="20" y="20" font-family="sans-serif" font-size="20px" fill="red">( 20, 20 )</text>
<text x="70" y="70" font-family="sans-serif" font-size="20px" fill="red">( 70, 70 )</text>
<circle cx="20" cy="20" r="20" fill="green"></circle>
<circle cx="70" cy="70" r="20" fill="purple"></circle></svg>
How can I adjust this?
You just need to draw your text nodes after drawing your circles.
//Circle Data Set
var circleData = [
{ "cx": 20, "cy": 20, "radius": 20, "color" : "green" },
{ "cx": 70, "cy": 70, "radius": 20, "color" : "purple" }];
//Create the SVG Viewport
var svgContainer = d3.select("#svgContainer")
.attr("width",200)
.attr("height",200);
// draw your circles and any other graphic elements first!
var circles = svgContainer.selectAll("circle")
.data(circleData)
.enter()
.append("circle")
.attr("cx", function(d) {return d.cx})
.attr("cy", function(d) {return d.cy})
.attr("r", function(d) {return d.radius})
.attr("fill", function(d) {return d.color})
// These will now be appended AFTER the circles
// When you use `append` it will add text nodes to end
// of svgContainer
var text = svgContainer.selectAll("text")
.data(circleData)
.enter()
.append("text");
// Here you are editing the pre-existing `text` nodes that you added above.
// Note that you don't use `append` here.
// Instead, you are modifying the d3 selection stored in `text`
var textLabels = text
.attr("x", function(d) { return d.cx; })
.attr("y", function(d) { return d.cy; })
.text( function (d) { return "( " + d.cx + ", " + d.cy +" )"; })
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");
Here is an edited version of your code:
http://jsfiddle.net/jrsxLfpg/2/