Published
Edited
Oct 1, 2021
1 fork
10 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require("d3@6")
Insert cell
Insert cell
visualization = {
// load the file
const text = await FileAttachment("beeswarm-observable-example.svg").text();
const document = (new DOMParser).parseFromString(text, "image/svg+xml");
// extrapolate the svg node from its original context
const svg = d3.select(document.documentElement).remove();
// replace 'width' and 'height' with 'viewbox'(to add responsiveness)
const _width = svg.attr("width");
const _height = svg.attr("height");
svg.attr("viewBox", `0 0 ${_width} ${_height}`);
svg.attr("width", null);
svg.attr("height", null);

// create a selection for all labels
const labels = svg.selectAll("g.labels text");
// hide all and remove pointer events
labels.style("opacity", 0);
labels.style("pointer-events", "none");

// create selection for all groups
const groups = svg.selectAll("g#viz > g:not(#axis) > g");
// set click events
groups.each(function(){
const _g = d3.select(this) // this group
const circles = _g.selectAll("circle"); // circles in this group
circles.style("cursor","pointer");
circles.each(function(d,i){
const index = i; // circle's index
d3.select(this).on("click",function(){
// find corresponding label
const l = _g.selectAll("text").filter(function(e,j){return j===index})
const currentOpacity = l.style("opacity")
// et voilà
if (currentOpacity==0) {
l.style("opacity", 1)
} else {
l.style("opacity", 0)
}
})
})
})
// return the svg
return svg.node();
}
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more