D3: getting data from SVG

Is it possible to get data from svg through d3?

I have the following scenario: on the Resize page I need to update the svg width that was generated on the server via d3. So, for example, the x axis. However, the client-side d3 library is not aware of svg. I noticed that with every DOM object there is an __ chart__ object. Is there a way to access the range and domain, for example, and update them accordingly?

+1
javascript svg
source share
1 answer

When you create an SVG on the server and pass it to the client, only the actual SVG DOM is passed, and not any javascript objects or properties (such as the d3 __data__ property) that you used to create it.

So, in order to attach data to SVG elements that are actually transferred along with the file, you will need to create an attribute of this element that contains the data. Then you can select the client side of the item and analyze the data attribute.

Example:

 /*** Server Side ***/ /* if `bars` is a d3 selection of rectangles in a bar graph */ bars.attr("data-name", function(d){return d.name;}) .attr("data-value", function(d) {return d.value;}); /*** Client Side ***/ var bars = d3.selectAll("rect.bar") .datum(function(){ return { name: this.getAttribute("data-name"), value: this.getAttribute("data-value") } }) .on("click", function(d,i){ /* do something with the data */ }); 

This works if the data in question is just a few numbers or names that you want to use in tooltips or similar interactions. It does not work for a complex object such as a chart function. If you need to redraw / resize the client part of the diagram, I really do not see any performance advantages when trying to draw servers on the graphs.

You can create server scripts to parse all your data in a ready-to-use format, perhaps even run d3 layout functions to create a ready-to-draw JSON array. But then draw a graph on the client side.

0
source share

All Articles