krishna_v
krishna_v

Reputation: 1511

d3.js - place text below the circle

I am displaying different radius circles with different color. I am trying to place the text(radius value) below each circle but not getting displayed though i could see the text in the browser inspector.

following is the code:

var width=960,height=500;
  var margin = {top: 29.5, right: 29.5, bottom: 29.5, left: 59.5};
  radiusScale = d3.scale.sqrt().domain([1, 100]).range([10, 39]),
    colorScale = d3.scale.category10();



// Create the SVG container and set the origin.
    var svg = d3.select("#chart").append("svg")
    .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
    .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");


    var i =0;

    while (i<=50)
    {

         console.log("i value is " + i + " value of scale " +i+ " is " + radiusScale(i));
        var circle = svg.append("g").append("circle")
                          .attr("id","circle" + i)
                          .attr("cx", i*12 )
                          .attr("cy", 20)
                          .attr("fill",colorScale(i))
                          .attr("r", radiusScale(i))
                  .append("text").attr("dx",i*12).text(function(d){return radiusScale(i)});


        i=i+10;

    }

should i be adding the text in svg instead of circle to display below the corresponding circles.

Upvotes: 1

Views: 2234

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

SVG will not display text appended to circle elements. You append to the g element:

var g = svg.append("g");
g.append("circle")
                      .attr("id","circle" + i)
                      .attr("cx", i*12 )
                      .attr("cy", 20)
                      .attr("fill",colorScale(i))
                      .attr("r", radiusScale(i));
g.append("text").attr("dx",i*12).text(function(d){return radiusScale(i)});

Also note that your function(d) in .text() isn't necessary, you can do just

g.append("text").attr("dx",i*12).text(radiusScale(i));

Upvotes: 3

Related Questions