Published
Edited
Oct 13, 2019
Importers
Insert cell
Insert cell
chart = {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);

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

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

svg
.append("g")
.attr("stroke-width", 1.5)
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.selectAll("g")
.data(data)
.join("g")
.attr(
"transform",
d => `translate(${x(d.x) + jitter()},${y(d.y) + jitter()})`
)
.call(g =>
g
.append("circle")
.attr("fill-opacity", 0.7)
.attr("fill", d => z(d[colorBy]))
.attr("r", 4)
.append("title")
.text(d => d.name)
);

return svg.node();
}
Insert cell
height = 600
Insert cell
margin = ({top: 20, right: 30, bottom: 30, left: 40})
Insert cell
x = d3.scaleLinear()
.domain(d3.extent(data, d => d.x)).nice()
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain(d3.extent(data, d => d.y)).nice()
.range([height - margin.bottom, margin.top])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x))
.call(g => g.select(".domain").remove())
.call(g => g.append("text")
.attr("x", width - margin.right)
.attr("y", -4)
.attr("fill", "#000")
.attr("font-weight", "bold")
.attr("text-anchor", "end")
.text(data.x))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.select(".domain").remove())
.call(g => g.select(".tick:last-of-type text").clone()
.attr("x", 4)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(data.y))
Insert cell
data = Object.assign(
await d3.csv(
"https://gist.githubusercontent.com/mbostock/77a98cd519be20ea1f8e33bbd3617ac2/raw/574433e95e983b288a54f4d2217cb39d1557cd8d/mtcars.csv",
({ name, mpg: x, hp: y }) => ({
name,
x: +x,
y: +y,
make: name.substr(name.indexOf(' '))
})
),
{ x: "Miles per gallon", y: "Horsepower" }
)
Insert cell
colorBy = 'make'
Insert cell
z = d3
.scaleOrdinal()
.domain(data.map(d => d[colorBy]))
.range(d3.schemeCategory10)
Insert cell
d3 = require("d3@5")
Insert cell
jitterValue = 5
Insert cell
// overlap prevention, based on https://observablehq.com/@john-guerra/overlapping-scatterplots
jitter = () => Math.random() * jitterValue - jitterValue / 2
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