I’ve been studying this example of how to embed a D3 chart in a tooltip of another D3 chart.
Given that Observable allows to you import a chart from another notebook. (e.g. import {chart as histogram} with {histogram_data as data} from "@mbostock/d3-histogram"), is it possible to use import to embed one chart into another, rather than writing the D3 for both all in one cell?
Yep, when you import a chart like in that example - {chart as histogram}, you can also embed it in another graphic if you’d like.
In that example, histogram is an HTML node - an SVG element that is the chart. So you can append it inside of another visualization if you want, instead of making it the main value of a cell.
The reason it’s “exploding” is that you have a circular dependency and are using side-effects.
The circular dependency is that the chart sets mutable hover_year, and top_10_manufacturers_for_year depends on hover_year, so whenever you assign to mutable hover_year, it re-evaluates the chart cell and creates a new chart from scratch.
The side-effect is that the chart cell appends the tooltip to the document.body, and so every time the chart cell is run, it adds a new tooltip to the body and never disposes the old tooltip.
There are ways to fix both of these problems… but it’ll take me a bit more time, so here’s a quick reply in the interim.
Here’s a quick sketch at an alternative design that’s easier to achieve: two charts in separate cells, with the second chart being derived from a subset of the data defined by the first chart.
It is possible to do this in a tooltip style, but you have to do some additional work to avoid the circular dependency problem.
Thanks for the insights, @mbostock. Sounds like if I want to embed a viz in a tooltip, I’m better off building it all in one cell (like the “finalCloro” example I originally linked to) rather than trying to piece it together via import.
The primary advantage of the second chart in a separate cell, rather than in a tooltip, is that you break the circular dependency: the first chart exposes its selection (the subdata) which then drives the second chart. You could still use imports to implement the charts separately; I did it in one notebook because it was quicker to sketch.
Here’s an update to the sketch that shows how to combine the two cells into a tooltip style:
To combine the cells, there’s a new cell at the top like so:
In addition, I changed the two charts definitions to wrap the returned cells in a DIV so as to prevent the inspector from displaying each chart in a separate cell.
// Wrap to prevent the inspector from displaying inline.
return document.createElement("div").appendChild(svg.node());