Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I append a literal SVG element with d3?

I'd like to append a literal SVG element with d3.

So instead of writing

svg.selectAll("circle")            
    .data(data)                    
    .enter()                       
    .append("circle")    // etc etc

I'd like to do:

svg.selectAll("circle")            
    .data(data)                    
    .enter()                       
    .append('<circle cx="158.9344262295082" cy="200" r="16" fill="red"></circle>')   

so that I could create a complex template elsewhere (for example with handlebars), and then compile it with data and append it.

like image 797
simone Avatar asked Oct 13 '16 23:10

simone


1 Answers

You can do this, although not via the selection.append() function. Instead you'd need to use the selection.html() function.

This would make it quite difficult to use in the context of data-joins, but not impossible. This is probably the best you could do, which involves adding an additional svg group to the DOM which may not be a bad thing anyway:

var svg = d3.selectAll("svg");
svg.selectAll("circle")            
       .data([50, 100, 150])                    
       .enter()                       
       .append("g")
       .attr("transform", function(d) { return "translate(" + [d, d] + ")"; })
       .html('<circle r="16" fill="red"></circle>');   
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="500"></svg>

I guess taking this answer a bit further, you could actually embed the result that you wish to render directly into your data object. So you've add some code that looked like:

.html(function(d) { return d.templatedHTML; });

At this point however stop and ask yourself the question: "What am I using D3 for?". D3 is described as

Data Driven Documents

If you're using something like handlebars, then you're taking away one of the core responsibilities that D3 was designed for (building some DOM from some data) and giving it to some other library.

I'm not stating you shouldn't do that (as you did mention complex templates) but do just ask yourself the question to make sure that it's a path you wish to go down.

like image 73
Ian Avatar answered Oct 11 '22 23:10

Ian