Public
Edited
Sep 27, 2022
Insert cell
# ex11: D3 in Observable
Insert cell
md`## Exercise 1`
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
svg.append('g')
.attr('fill', 'steelblue')
.selectAll('rect')
.data(data)
.join('circle')
.attr('cx', d => d.x)
.attr('cy', d => d.y)
.attr('r', d => d.r);
return svg.node();
}
Insert cell
data = [{x: 20, y: 20, r: 10},
{x: 50, y: 50, r: 30},
{x: 80, y: 80, r: 10}];
Insert cell
height = 100;
Insert cell
width = 100;
Insert cell
d3 = require("d3@7")
Insert cell
md`## Exercise 2`
Insert cell
import {BarChart} from "@d3/bar-chart"
Insert cell
chart2 = BarChart(alphabet, {
x: d => d.letter,
y: d => d.frequency,
xDomain: d3.groupSort(alphabet, ([d]) => -d.frequency, d => d.letter), // sort by descending frequency
yFormat: "%",
yLabel: "↑ Frequency",
width: 1000,
height: 500,
color: "steelblue"
})
Insert cell
alphabet = FileAttachment("alphabet.csv").csv({typed: true})
Insert cell
md`## Exercise 4`
Insert cell
import {BubbleMap} from "@d3/bubble-map"
Insert cell
population = FileAttachment("population.json").json()
Insert cell
chart3 = BubbleMap(population, {
value: ([population]) => +population,
position([, stateid, countyid]) {
const county = countymap.get(stateid + countyid);
return county && centroid(county);
},
title([population, stateid, countyid]) {
const state = statemap.get(stateid);
const county = countymap.get(stateid + countyid);
return `${county?.properties.name}, ${state?.properties.name}\n${(+population).toLocaleString("en")}`;
},
features: nation,
borders: statemesh,
width: 975,
height: 610
})
Insert cell
centroid = {
const path = d3.geoPath();
return feature => path.centroid(feature);
}
Insert cell
us = FileAttachment("counties-albers-10m.json").json()
Insert cell
nation = topojson.feature(us, us.objects.nation)
Insert cell
statemap = new Map(topojson.feature(us, us.objects.states).features.map(d => [d.id, d]))
Insert cell
countymap = new Map(topojson.feature(us, us.objects.counties).features.map(d => [d.id, d]))
Insert cell
statemesh = topojson.mesh(us, us.objects.states, (a, b) => a !== b)
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