how to use d3 to append fragment returned by svg``

Hi!

I’m generating an svg fragment in one cell using svg`` , and I’d like to use d3 in another cell to append that fragment to a plot generated by Plot. Can d3 attach a fragment returned by one cell to an svg constructed in another cell all in one go?

There’s two reasons I’d like to do this. First, the contents of the fragment that I want to append to the plot are really complex. So it’s easier to keep things straight by constructing the fragment in a separate place in my code using svg`` , instead of constructing it piece-by-piece with dozens of calls to .append and .attr. Second, I want the fragment I’m constructing to include math typset with tex`` . It’s not obvious to me how to use tex`` in combination with d3 to add math to an svg, so I’m trying to separate out the work into two cells (one to construct the fragment, the other to insert the fragment into the svg containing the plot).

Here’s the basic structure I have in mind (obviously, this doesn’t work):

cell constructing svg fragment:

fragment = svg`<g> ...  </g>`

cell creating plot and then adding fragment to plot using d3:

{
lp = Plot(...)
d3.select(lp).append(fragment)
return lp
}

FWIW, I’m not attached to using d3 for this. All that’s really important to me is to construct the fragment in its own cell and then append the fragment to the plot elsewhere. Just guessing d3 is the tool for the job.

1 Like

I think the easiest way to accomplish this is to include a function as a mark. As far as I know, this is undocumented but here’s an example:

2 Likes

Beautiful! Thank you.

1 Like

It is documented (“Marks may also be a function which returns an SVG element, if you wish to insert some arbitrary content into your plot.”). Cheers