Published
Edited
Oct 1, 2021
Insert cell
Insert cell
d3 = require("d3@6")
Insert cell
visualization = {
// Load and parse the file
const text = await FileAttachment("beeswarm.svg").text()
const document = (new DOMParser).parseFromString(text, "image/svg+xml")

// extrapolate the svg form its original context
const svg = d3.select(document.documentElement).remove()
const _width = svg.attr("width")
const _heigh = svg.attr("height")
svg.attr("viewBox", "0 0 1280 720")
svg.attr("width", null)
svg.attr("height", null)

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

// create a selection for all the groups
const groups = svg.selectAll("g#viz > g:not(#axis) > g")

//set interactive behaviours
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;
d3.select(this).on("click", function(){
// find the corresponding label
const _l = _g.selectAll("text").filter(function(e,j){return j===index})
// check the current opacity
const currentOpacity = _l.style("opacity")
// set opacity
if (currentOpacity==0) {
_l.style("opacity", 1)
} else {
_l.style("opacity", 0)
}
})
})

})

// return to observable the svg node
return svg.node()
}
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