Published
Edited
Jul 29, 2019
Insert cell
Insert cell
d3 = require("d3@5")
Insert cell
html`<div id="wrapper"></div>`
Insert cell
dataset = await d3.json("https://raw.githubusercontent.com/chekos/test-data/master/nyc_weather_data.json")
Insert cell
yAccessor = d => d.temperatureMax
Insert cell
dateParser = d3.timeParse("%Y-%m-%d")
Insert cell
xAccessor = d => dateParser(d.date)
Insert cell
dimensions = ({
width: width,
height: 300,
margin: ({
top: 15,
right: 15,
bottom: 60,
left: 40
})
})
Insert cell
dimensions.boundedWidth = dimensions.width - dimensions.margin.right - dimensions.margin.left
Insert cell
dimensions.boundedHeight = dimensions.height - dimensions.margin.top - dimensions.margin.bottom
Insert cell
wrapper = d3.select("#wrapper")
.append("svg")
.attr("width", dimensions.width)
.attr("height", dimensions.height)
Insert cell
bounds = wrapper.append("g")
.style("transform", `translate(${
dimensions.margin.left
}px, ${
dimensions.margin.top
}px)`)
Insert cell
yScale = d3.scaleLinear()
.domain(d3.extent(dataset, yAccessor))
.range([dimensions.boundedHeight, 0])
Insert cell
freezingTemperaturePlacement = yScale(32)
Insert cell
freezingTemperatures = bounds.append("rect")
.attr("x", 0)
.attr("width", dimensions.boundedWidth)
.attr("y", freezingTemperaturePlacement)
.attr("height", dimensions.boundedHeight
- freezingTemperaturePlacement)
.attr("fill", "#e0f3f3")
Insert cell
xScale = d3.scaleTime()
.domain(d3.extent(dataset, xAccessor))
.range([0, dimensions.boundedWidth])
Insert cell
lineGenerator = d3.line()
.x(d => xScale(xAccessor(d)))
.y(d => yScale(yAccessor(d)))
Insert cell
line = bounds.append("path")
.attr("d", lineGenerator(dataset))
.attr("fill", "none")
.attr("stroke", "#19267c")
.attr("stroke-width", 1.2)
Insert cell
yAxisGenerator = d3.axisLeft()
.scale(yScale)
Insert cell
yAxis = bounds.append("g")
.call(yAxisGenerator)
Insert cell
xAxisGenerator = d3.axisBottom()
.scale(xScale)
Insert cell
xAxis = bounds.append("g")
.call(xAxisGenerator.ticks(width / 80))
.style("transform", `translateY(${
dimensions.boundedHeight
}px)`)
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