Saqib Ali
Saqib Ali

Reputation: 12545

Can d3.js circle's radius be specified by a style attribute?

This explainer shows how d3.js style attributes can be used to vary the appearance of a circle (fillcolor, stroke-color, stroke-width, etc).

Can I set the radius of a d3.js circle using a style attribute?

Upvotes: 2

Views: 2210

Answers (2)

SiddP
SiddP

Reputation: 1663

yes you can. But its better to use attr for DOM value manipulations and style for css.

             svg.selectAll(".dot")
                .data(data)
                .enter().append("circle")
                .attr("class", "dot")
                .style("r", 3)
                .attr("cx", function(d) {
                  return x(d.date);
                }
                )
                .attr("cy", function(d) {
                  return y(d.value);
                })
                .attr("stroke", function(d) {
                  return color(this.parentNode.__data__.name)
                })
                .attr("fill", function(d) {
                  return color(this.parentNode.__data__.name)
                })

Example using style and example using attr though both work just same way but have a look at the structure of DOM.

Using attr:

`<circle class="dot" r="3" cx="0" cy="174.375" stroke="#1f77b4" fill="#1f77b4"></circle>`

Using style:

`<circle class="dot" cx="0" cy="174.375" stroke="#1f77b4" fill="#1f77b4" style="r: 3;"></circle>`

Upvotes: 2

Gilsha
Gilsha

Reputation: 14591

You can set radius of circle as attribute OR style.

But, if you specify an attr("r"), but you have a css style such as circle {r: 50;}, the style-sheet always takes priority over the attributes.

However, if you switch to using style("r"), then the element-specific style takes priority because it is more specific, as you would expect.

So you can use these based on the precedence.

//circle 1
d3.select("svg")
  .append("circle")
  .attr("cx", 50)
  .attr("cy", 50)
  .attr("r", 10); // Radius 10 as attribute

//circle 2
d3.select("svg")
  .append("circle")
  .attr("cx", 150)
  .attr("cy", 50)
  .style("r", 10); //Radius 10 as inline style 
/*External styles*/

circle {
  fill: green;
  r: 50;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg height=500 width=500></svg>

Upvotes: 5

Related Questions