Appending Color Legend to D3 SVG

Hi,

The Observable/D3 Color Legend function (Color Legend / D3 | Observable) is very helpful.

As well as generating a legend within it’s own cell, is there any way of referencing the generated legend SVG and adding it to a D3 SVG?

Basically, it would be nice to be able to include the legend “within” a chart, so it gets output along with the chart (for print/export/etc).

This would be a nice feature within the Observable platform too, as having 2 cells per chart makes it tricky to export/embed.

But in this case is there anyway of calling the legend svg from within some d3 SVG code?

Thanks

Mike

2 Likes

SVG is itself a legal SVG element. Thus, you can simply append it directly. Here’s an example:

Alternatively, you could create a statically positioned div, append your SVG, and then append another absolutely placed div containing the legend. The advantage is that the legend need not be an SVG; it could be HTML, as is produced by Swatches. Here’s another example:

3 Likes

Thanks so much @mcmcclur !!

Your first solution is what I was hoping for, but I couldn’t get the syntax right, so that’s perfect.
I like having the legend as part of the SVG so they export “as one” (as PNG or SVG).

It would be great if @mbostock’s excellent d3 color legend function could do the ordinal horizontal/vertical legend too, rather than leaning on the Swatches HTML, as this is the layout I probably use the most (I’ve been using Susie Lu’s d3-legend (https://d3-legend.susielu.com/) for vertical ordinal and rolling my own for horizontal).

Thanks again!!

Thanks

Yes, I agree - that is an issue with the second approach. The first approach gives you the whole image as one SVG and even prints well, too, from Chrome.