Public
Edited
Nov 30, 2022
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

const tooltip = new Tooltip()

svg.append("g")
.call(xAxis);

svg.append("g")
.call(yAxis);

const color = d3.scaleSequential().domain(d3.extent(data, d => d.culmen_depth_mm)).interpolator(d3.interpolatePuRd);


svg.append("g")
.selectAll("circle")
.data(data)
.join("circle")
.filter(d => d.body_mass_g)
.attr("cx", d => x(d.flipper_length_mm))
.attr("cy", d => y(d.body_mass_g))
.attr("r", 2)

svg.append("g")
.selectAll('path')
.data(data)
.join('path')
.attr("fill", d => color(d.culmen_depth_mm))
.attr("stroke", "#FFF")
.attr('opacity', .3)
.attr("d", (d, i) => voronoi.renderCell(i))
.on("mouseover", (event, d) => tooltip.show(d) )

svg.append(() => tooltip.node)


return svg.node();
}
Insert cell
data = FileAttachment("penguins.csv").csv({typed: true})
Insert cell
coords = data.map(d => [x(d.flipper_length_mm), y(d.body_mass_g)])
Insert cell
delaunay = d3.Delaunay.from(coords)
Insert cell
voronoi = delaunay.voronoi([margin.left, 0, width - margin.right, height - margin.top])
Insert cell
delaunay.render()
Insert cell
height = 600
Insert cell
x = d3.scaleLinear()
.domain(d3.extent(data, d => d.flipper_length_mm)).nice()
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain(d3.extent(data, d => d.body_mass_g)).nice()
.range([height - margin.bottom, margin.top])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
Insert cell
margin = ({top: 25, right: 20, bottom: 35, left: 40})
Insert cell
d3 = require("d3@6")
Insert cell
class Tooltip {
constructor() {
this._name = htl.svg`<text font-size = '14px' font-weight = 'bold' stroke = '#FFF' stroke-width = '1px' paint-order = 'stroke fill'></text>`;
this.node = htl.svg`<g pointer-events="none" display="none" font-family="sans-serif" font-size="10" text-anchor="middle">
${this._name}
</g>`;
}
show(d) {
this.node.removeAttribute("display");
this.node.setAttribute("transform", `translate(${x(d.flipper_length_mm)},${y(d.body_mass_g)})`);
this._name.textContent = d.flipper_length_mm
}
hide() {
this.node.setAttribute("display", "none");
}
}
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more