Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 Selecting an element inside an SVG

I am trying to create some graphs in D3. So far love it, but I'm getting a bit stuck. I want to create one area to hold the data points and another to hold the axis and labels. I think I will go even more fine grained than that to make updating the graph more efficient. But the issue I am having is that I can't seem to select sub elements within the SVG.

Here is what I have:

var graph = d3.select('#Graph svg')
if (graph[0][0] == null){
    graph = d3.select('#Graph')
        .append("svg:svg")
        .attr("width",width)
        .attr("height",height)
        .attr("class","chart");
}

graph.append("svg:g")
    .attr("id","data")

Now I have not found a way to select that data container. I have tried

d3.select("#Graph svg data")

But no luck. Any Ideas?

like image 699
Dan Walmsley Avatar asked Feb 17 '12 04:02

Dan Walmsley


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.

Which tag is used for marking points in d3 using SVG?

An SVG line element is represented by <line> tag. A line's attributes are: x1: This is the x-coordinate of the first point. y1: This is the y-coordinate of the first point.

What does d3 selectAll return?

selectAll() function in D3. js is used to select all the element that matches the specified selector string. Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.

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.


2 Answers

Let's try this code.

d3.select("#Graph svg").selectAll("g") 

"g" means to select all node "g" under svg node.

like image 103
lahphim Avatar answered Sep 20 '22 02:09

lahphim


When creating your data container with append(), you can save it as a selection to a variable.

var dataContainer = graph.append("svg:g")     .attr("id","data"); 

If done in this way, you won't ever need to make the d3 selection again (in a similar way you have done with var graph on the 1st line of the code in your question), because a reference to this selection is already stored in your var dataContainer.

like image 33
ksav Avatar answered Sep 22 '22 02:09

ksav