invisible text inside svg text element - javascript

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>

Related

Draw circles with text in the middle using Javascript/CSS [duplicate]

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.

How to place rectangles behind text in d3.js

I am having difficulty trying to place rectangles behind text as background in d3.js. I read that in order to do that you have to append to the same g element but in my case it does not work like that.
my code: plunker
var urls = [{
"wor": "Nordmerika",
"number": "10.9",
"lon": "-100.33",
"lat": "47.61"
}, {
"wor": "Latinamerika",
"number": "14.2",
"lon": "-56.62",
"lat": "-8.53"
}, {
"wor": "Afrika",
"number": "51.8",
"lon": "24.5085",
"lat": "8.7832"
}, {
"wor": "Asien",
"number": "27.5",
"lon": "104.238281",
"lat": "34.51561"
}, {
"wor": "GUS | Russland",
"number": "3.4",
"lon": "62.753906",
"lat": "47.923705"
}, {
"wor": "Europa | MSOE",
"number": "10.9",
"lon": "15.2551",
"lat": "54.526"
}]
//starting map
var margin = {
top: 10,
left: 10,
bottom: 10,
right: 10
},
width = parseInt(d3.select('#map').style('width')),
width = width - margin.left - margin.right,
mapRatio = .5,
height = width * mapRatio;
//Map projection
var projection = d3.geo.equirectangular()
.scale(width / 5.8)
.translate([width / 2, height / 2]) //translate to center the map in view
//Generate paths based on projection
var path = d3.geo.path()
.projection(projection);
//Create an SVG
var svg = d3.select("#map")
.append("svg")
.attr("viewBox", "0 0 " + width + " " + height)
.attr("preserveAspectRatio", "xMinYMin");
//Group for the map features
var features = svg.append("g")
.attr("class", "features");
var labelWidths = [];
d3.json("countries.topojson", function(error, geodata) {
if (error) return console.log(error); //unknown error, check the console
var layerOne = svg.append("g");
var layerTwo = svg.append("g");
var layerThree = svg.append("g");
//Create a path for each map feature in the data
features.selectAll("path")
.data(topojson.feature(geodata, geodata.objects.subunits).features) //generate features from TopoJSON
.enter()
.append("path")
.attr("d", path)
.on("click", clicked)
.style('fill', '#cdd5db')
.style('stroke', '#ffffff')
.style('stroke-width', '0.5px')
.on('mouseover', function(d, i) {
d3.select(this).style('stroke-width', '2px');
})
.on('mouseout', function(d, i) {
d3.select(this).style('stroke-width', '0.5px');
});
var bubbles = layerOne.attr("class", "bubble")
.selectAll("circle")
.data(urls)
.enter()
.append("circle")
.attr("cx", function(d, i) {
return projection([d.lon, d.lat])[0];
})
.attr("cy", function(d, i) {
return projection([d.lon, d.lat])[1];
})
.attr("r", function(d) {
if (width >= 1000) {
return (d.number)
} else {
return d.number
}
})
.style('fill', function(d) {
if (d.wor == 'Afrika') {
return '#dc0f6e'
} else {
return '#3e3e3e'
}
});
var text = layerTwo
.attr('class', 'text')
.selectAll('text')
.data(urls)
.enter()
.append('text')
.attr('x', function(d, i) {
if (d.number < 10) {
return projection([d.lon, d.lat])[0] + 60;
} else {
return projection([d.lon, d.lat])[0]
}
})
.attr('y', function(d, i) {
return projection([d.lon, d.lat])[1];
})
.text(function(d) {
return d.number;
})
.attr("dy", function(d) {
if (this.getBBox().width > d.number * 3) {
return '-2em'
} else {
return "0.3em"
}
})
.attr("text-anchor", "middle")
.style('fill', '#fff')
.style('font-weight', 'bold')
.style('font-size', '1em');
var labels = layerThree
.attr('class', 'labels')
.selectAll('text')
.data(urls)
.enter()
.append('text')
.attr('x', function(d, i) {
return projection([d.lon, d.lat])[0] + 60;
})[plunker][1]
.attr('y', function(d, i) {
return projection([d.lon, d.lat])[1];
})
.attr("text-anchor", "middle")
.text(function(d) {
return d.wor;
})
.attr('dy', function(d) {
labelWidths.push(this.getBBox().width)
var radius = d.number * 2
if (radius > 10) {
return d.number * 4;
} else {
return '-0.5em'
}
})
.style('font-size', '1em')
.style('font-weight', 'bold');
var rect = layerThree
.attr('class', 'rectlabels')
.selectAll('rect')
.data(urls)
.enter()
.append('rect')
.attr('x', function(d, i) {
return projection([d.lon, d.lat])[0] + 60;
})
.attr('y', function(d, i) {
return projection([d.lon, d.lat])[1];
})
.attr('dy', function(d) {
return '1em'
})
.style('fill', '#ffffff')
.attr('width', function(d, i) {
return labelWidths[i] / 10 + 'em'
})
.attr('height', '1em');
function clicked(d, i) {
}
});
It looks like the rectangles don't line up correctly with the text, there are a couple of reasons for this:
Your <text> is anchored at the middle, and your <rects> are anchored at the top-left point of the <rect>.
You're setting dy on your <text> elements at varying amounts, this moves the text down by that distance, but all your <text> elements have dy=1em, so they're not moving down by the same amount.
I would suggest that you create 6 <g> elements, one for each label, each containing the <rect> element and the <text> element. Then you only need to set x & y attributes on the <g> element, and it's children should stay together.
I think you should also try removing the text-anchor attribute, and instead move the <g> element left by half its width ((labelWidths[i] / 10) / 2) to get it to center over the coordinates. This is made difficult by the fact that your width is in em units, so you might need to do it in pixels and adjust accordingly.
Try it without the dy elements too and see if that helps with the vertical alignment.

Text label hides behind the circle node in d3.js [duplicate]

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.

Stacked D3JS Bubble Chart

Hey I'm using D3JS as a chart library and I'm really interested in exploiting the cool features in the Bubble Chart. On the main D3JS chart site the following Bubble Chart is used to compare two sets of data:
Bubble Chart.
I was wondering if anybody actually had any idea of how to create a bubble chart like this, I'm struggling to get it work past using a size variable.
I just really want to be able to compare two sets of data for example:
Hostnames (45,955,158) VS Active Sites (21,335,629)
The code I am using is below, I use JSON to retrieve my data, I'm a major newbie when it comes to js and even more so this jQuery library so would appreciate any help.
index.html
<div class="four columns browserstats2003">
<h3>Browser Stats 2003</h3>
</div>
<div class="four columns mobilephonestats">
<h3>Smartphone Sales 2003</h3>
<p>The first smartphone had not been released in 2003.</p>
<div id=""></div>
</div>
mobile.json
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{"name": "Smartphone Sales", "size": 11111},
{"name": "Smartphone Salesa", "size": 2111}
]
}
]
}
]
}
js/js.js
// JavaScript Document
$(document).ready(function () {
// 2003 bubble chart
var diameter = 360,
format = d3.format(",d"),
color = d3.scale.category20c();
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(1.5);
var svg = d3.select(".mobilephonestats").append("svg")
.attr("width", diameter)
.attr("height", diameter)
.attr("class", "bubble");
d3.json("mobile.json", function(error, root) {
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(root))
.filter(function(d) { return !d.children; }))
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
node.append("title")
.text(function(d) { return d.className + ": " + format(d.value); });
node.append("circle")
.attr("r", function(d) { return d.r; })
.style("fill", function(d) { return color(d.packageName); });
node.append("text")
.attr("dy", ".3em")
.style("text-anchor", "middle")
.text(function(d) { return d.className.substring(0, d.r / 3); });
});
// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
var classes = [];
function recurse(name, node) {
if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
else classes.push({packageName: name, className: node.name, value: node.size});
}
recurse(null, root);
return {children: classes};
}
d3.select(self.frameElement).style("height", diameter + "px");
// end bubble year
});
In the example you provided, he's definitely using a force layout, which is a bit more complicated that the Bubble Chart you're using. You'll have to take into consideration things like collisions and animation.
Why not just have a look at the JavaScript he used to generate it.
Jim Vallandingham wrote an extensive tutorial on Bubble Clouds, which should get you started.
To create the split in the middle of the cirlce as a way of doing some form of data comparison, "clip-paths" are the way forward:
Append two circles, one for each data-set.
Append two clip-path, one for each data-set
Append a rectange to each clip-path.
Set the rectangle x attributes and width, which defines the position of the split in the middle. This has to be a function of the data.
Crop the rectangles and circles
Here's the code:
var nodeEnter = node.enter().append("a")
.attr("class", "g-node")
.call(force.drag);
var democratEnter = nodeEnter.append("g")
.attr("class", "g-democrat");
democratEnter.append("clipPath") // clip-path to crop the rectangle
.attr("id", function(d) { return "g-clip-democrat-" + d.id; })
.append("rect");
democratEnter.append("circle");
var republicanEnter = nodeEnter.append("g")
.attr("class", "g-republican");
republicanEnter.append("clipPath") // Clip-path to crop the rectangle
.attr("id", function(d) { return "g-clip-republican-" + d.id; })
.append("rect");
republicanEnter.append("circle");
node.selectAll("rect")
.attr("y", function(d) { return -d.r - clipPadding; })
.attr("height", function(d) { return 2 * d.r + 2 * clipPadding; });
// Defining the x-attr and width of the rectangle, which effectively splits the circle
node.select(".g-democrat rect")
.attr("x", function(d) { return -d.r - clipPadding; })
.attr("width", function(d) { return 2 * d.r * d.k + clipPadding; });
node.select(".g-republican rect")
.attr("x", function(d) { return -d.r + 2 * d.r * d.k; })
.attr("width", function(d) { return 2 * d.r; });
// Setting the clip-path to crop the circles
node.select(".g-democrat circle")
.attr("clip-path", function(d) { return d.k < 1 ? "url(#g-clip-democrat-" + d.id + ")" : null; });
node.select(".g-republican circle")
.attr("clip-path", function(d) { return d.k > 0 ? "url(#g-clip-republican-" + d.id + ")" : null; });
This should generate something like this:
<g class="g-democrat">
<clipPath id="g-clip-democrat-43">
<rect y="-63.36487389363757" height="126.72974778727514" x="-63.36487389363757" width="59.449375597303515">
</rect>
</clipPath>
<circle clip-path="url(#g-clip-democrat-43)" r="59.36487389363757">
</circle></g>
<g class="g-republican">
<clipPath id="g-clip-republican-43">
<rect y="-63.36487389363757" height="126.72974778727514" x="-3.915498296334057" width="118.72974778727514">
</rect>
</clipPath>
<circle clip-path="url(#g-clip-republican-43)" r="59.36487389363757">
</circle></g>

d3 add text to circle

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)

Categories

Resources