Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  62] [ 5]  / answers: 1 / hits: 117212  / 12 Years ago, wed, november 28, 2012, 12:00:00

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?


More From » svg

 Answers
45

Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:


enter


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/


[#81734] Wednesday, November 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
malkajillc

Total Points: 652
Total Questions: 107
Total Answers: 98

Location: Finland
Member since Sat, Nov 6, 2021
3 Years ago
malkajillc questions
;