Published
Edited
Aug 28, 2020
1 star
Insert cell
md ` # Chapter 2
Making a scatterplot! Joins, circles, axes, oh my!`
Insert cell
html `<div id="wrapper"></div>`
Insert cell
data = [
{x:1, y:1},
{x:2, y:2},
{x:3, y:3},
{x:4, y:4},
{x:5, y:5}
]
Insert cell
xAccessor = d => d.x
Insert cell
yAccessor = d => d.y
Insert cell
width = d3.min([
500,
500
])
Insert cell
dimensions = [
{
width: width,
height: width,
margin: {
top: 10,
right: 10,
bottom: 50,
left: 50,
}, }
]
Insert cell
dimensions.boundedWidth = dimensions[0].width
- dimensions[0].margin.left
- dimensions[0].margin.right

Insert cell
dimensions.boundedHeight = dimensions[0].height
- dimensions[0].margin.top
- dimensions[0].margin.bottom
Insert cell
wrapper = d3.select("#wrapper") .append("svg")
.attr("width", dimensions[0].width)
.attr("height", dimensions[0].height)
Insert cell
bounds = wrapper.append("g") .style("transform", `translate(${
dimensions[0].margin.left
}px, ${ dimensions[0].margin.top
}px)`)
Insert cell
xScale = d3.scaleLinear()
.domain(d3.extent(data, xAccessor))
.range([0, dimensions.boundedWidth])
.nice()
Insert cell
yScale = d3.scaleLinear()
.domain(d3.extent(data, yAccessor))
.range([dimensions.boundedHeight, 0])
.nice()
Insert cell
dots = bounds.selectAll("circle") .data(data)
.enter().append("circle")
.attr("cx", d => xScale(xAccessor(d)))
.attr("cy", d => yScale(yAccessor(d)))
.attr("r", 5)
.attr("fill", d => colorScale(colorAccessor(d)))
Insert cell
xAxisGenerator = d3.axisBottom() .scale(xScale)
Insert cell
xAxis = bounds.append("g") .call(xAxisGenerator)
.style("transform", `translateY(${dimensions.boundedHeight}px)`)
Insert cell
xAxisLabel = xAxis.append("text")
.attr("x", dimensions.boundedWidth / 2)
.attr("y", dimensions[0].margin.bottom - 10)
.attr("fill", "black")
.style("font-size", "1.4em")
.html("Dew point (&deg;F)")
Insert cell
yAxisGenerator = d3.axisLeft() .scale(yScale)
.ticks(4)
Insert cell
yAxis = bounds.append("g") .call(yAxisGenerator)
Insert cell
yAxisLabel = yAxis.append("text")
.attr("x", -dimensions.boundedHeight / 2)
.attr("y", -dimensions[0].margin.left + 10)
.attr("fill", "black")
.style("font-size", "1.4em")
.text("Relative humidity")
.style("transform", "rotate(-90deg)")
.style("text-anchor", "middle")
Insert cell
colorAccessor = d => d.y
Insert cell
colorScale = d3.scaleLinear()
.domain(d3.extent(data, colorAccessor))
.range(["skyblue", "darkslategrey"])
Insert cell
d3 = require("d3@5")
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