Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append SVG canvas to element other than body using D3

Tags:

Is it possible to append an SVG canvas to an element other than <body> using D3.js if the script is not inside that element?

For example, the code below does not work:

<html>
<body>
<script src="../../d3.v2.js"></script>
<script>
    var vis = d3.select("#container")
        .append("svg:svg")
          .attr("width",w)
          .attr("height",h);
</script>

<div id="container"></div>

</body>

All examples I have seen use d3.select("body").append.... but clearly we don't always want to append the canvas immediately to the body.

I found that if the <script> is inside the container div then I can use d3.select("#container") but it seems strange to me that I would have to include my script inside of the specific container(s) where I want the canvas.

like image 211
Gilman Avatar asked Dec 13 '12 17:12

Gilman


People also ask

Can we group SVG elements in d3js?

The <g> SVG element is a container used to group other SVG elements. Transformations applied to the <g> element are performed on its child elements, and its attributes are inherited by its children. We can create a group element with D3. js by appending a g element using any selection.

How is SVG used with D3?

SVG stands for Scalable Vector Graphics. SVG is an XML-based vector graphics format. It provides options to draw different shapes such as Lines, Rectangles, Circles, Ellipses, etc. Hence, designing visualizations with SVG gives you more power and flexibility.

Does D3 use SVG or canvas?

D3 charts are most often rendered using SVG, a retained mode graphics model, which is easy to use, but performance is limited. SVG charts can typically handle around 1,000 datapoints. Since D3 v4 you've also had the option to render charts using canvas, which is an immediate mode graphics model.


1 Answers

You're trying to select #container before it exists. You'll need to put your code in an onload or move the script below #container in the page.

like image 153
Zikes Avatar answered Nov 10 '22 06:11

Zikes