create svg elements in d3js
In D3.js, you can create SVG elements using the append()
method and the svg
namespace. Here's an example of creating a circle element using D3.js:
var svg = d3.select("body") .append("svg") .attr("width", 200) .attr("height", 200); var circle = svg.append("circle") .attr("cx", 100) .attr("cy", 100) .attr("r", 50) .attr("fill", "blue");
In this example, we're selecting the body
element using d3.select()
. We're then appending an SVG element using append()
and setting its width and height using the attr()
method. We're creating a circle element using the append()
method again and setting its cx
, cy
, r
, and fill
attributes using the attr()
method.
You can create other SVG elements in a similar way, using the append()
method and the appropriate SVG namespace. For example, to create a rectangle element, you could use the following code:
var rectangle = svg.append("rect") .attr("x", 50) .attr("y", 50) .attr("width", 100) .attr("height", 50) .attr("fill", "red");
In this example, we're creating a rectangle element using append()
and setting its x
, y
, width
, height
, and fill
attributes using the attr()
method.