Draw circles using D3

Abdelrahman Shoman picture Abdelrahman Shoman · Aug 15, 2013 · Viewed 23.7k times · Source

The following code is supoosed to draw five circles next to each other

<head>
<script type='text/javascript' src='jquery-2.0.3.min.js'></script>
<script type='text/javascript' src='knockout-2.3.0.js'></script>
<script type='text/javascript' src='knockout-2.3.0.js'></script>
<script type='text/javascript' src='knockout-2.3.0.js'></script>
<script src="bootstrap.min.js"></script>

<!-- Bootstrap -->
<link href="bootstrap.min.css" rel="stylesheet" media="screen">
<link href="sticky-footer.css" rel="stylesheet">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

</head>

<body>
  <div id="viz"></div>

<script type="text/javascript">
    var dataset = [],
    i = 0;

    for(i=0; i<5; i++){
        dataset.push(Math.round(Math.random()*100));
    }        

    var sampleSVG = d3.select("#viz")
        .append("svg")
        .attr("width", 400)
        .attr("height", 400);    

    sampleSVG.selectAll("circle")
        .data(dataset)
        .enter().append("circle")
        .style("stroke", "gray")
        .style("fill", "black")
        .attr("height", 40)
        .attr("width", 75)
        .attr("x", 50)
        .attr("y", 20);

  </script>
 </html>

It is not really my code I just copied it from this website http://christopheviau.com/d3_tutorial/

The problem is that this code does not draw any circle. Although that when I try to use the chrome's tool inspect element, I find that the circles are there but they are not visible.

I thought that the reason is the white colour of the circles although the stroke is not. However changing the colour was not really useful.

And the problem is that Dreamweaver is not really helping as it does for HTML or JavaScript for example.

Any suggestions for the solution of this issue, or any recommendation for the editor ?

Answer

Robert Longson picture Robert Longson · Aug 15, 2013

It looks like you took an example that generated rectangles and changed it to circles but circles don't have x, y, height and width attributes, they have cx, cy and radius attributes instead.

sampleSVG.selectAll("circle")
    .data(dataset)
    .enter().append("circle")
    .style("stroke", "gray")
    .style("fill", "black")
    .attr("r", 40)
    .attr("cx", 50)
    .attr("cy", 20);

Will draw multiple circles one on top of another.