Public
Edited
Sep 21, 2021
8 stars
Insert cell
Insert cell
Insert cell
{
let data = d3.range(10).map(d3.randomInt(1, 10));

// We'll select the tallest and shortest bars
let M = d3.max(data);
let m = d3.min(data);

// The basic Plot
let plot = Plot.plot({
marks: [
Plot.barY(data, {
x: (_, i) => i,
fill: (d) => d,
title: (d) => d
}),
Plot.ruleY([0])
]
});

// The bars are represented by SVG rects. We can select all of them
// and add a highlight on hover.
let nodes = d3
.select(plot)
.selectAll("rect")
.on("pointerenter", function () {
d3.select(this).attr("stroke-width", "2px").attr("stroke", "black");
})
.on("pointerleave", function () {
d3.select(this).attr("stroke", null);
})

// Next, we add a tippy tooltip to just the tallest and
// and shortest bars.
.nodes()
.forEach(function (bar) {
let value = d3.select(bar).select("title").text();
if (value == M) {
tippy(bar, {
content: `The max is ${M}!`
});
} else if (value == m) {
tippy(bar, {
content: `The min is ${m}!`
});
}
});

// Finally, we can remove the titles, if we like.
d3.select(plot).selectAll("rect").select("title").remove();

return plot;
}
Insert cell
tippy = require("tippy.js@6")
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