Published
Edited
Jun 29, 2020
1 fork
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.attr("id", "chart");

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

svg.append("g")
.call(yAxis);
svg.append("path")
.datum(data)
.attr("fill", "none")
.attr("class", "line")
.attr("stroke-width", 1.5)
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("d", line);
return svg.node();
}
Insert cell
height = 500
Insert cell
yTickSize = 35
Insert cell
margin = ({top: 20, right: 20, bottom: 40, left: yTickSize})
Insert cell
x = d3.scaleUtc()
.domain(d3.extent(data, d => d.date))
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)]).nice()
.range([height - margin.bottom, margin.top])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).ticks(width / 100).tickSizeOuter(0))
.call(g => g.selectAll(".tick text") // tick labels
.attr("class", "xsmall-copy"))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left + 1},0)`)
.call(d3.axisLeft(y).ticks(6).tickSize(yTickSize)) // left axis
.attr("stroke-opacity", 0.05)
.call(g => g.selectAll(".tick line").clone() // grid lines
.attr("stroke-opacity", 0.05)
.attr("x2", width - margin.left - margin.right))
.call(g => g.select(".tick:first-of-type") // first tick opacity
.attr("stroke-opacity", 1))
.call(g => g.selectAll(".tick text") // tick labels
.style("text-anchor", "start")
.attr("x", -yTickSize)
.attr("y", -9)
.attr("class", "xsmall-copy"))
.call(g => g.select(".domain").remove()) // remove domain line
.call(g => g.select(".tick:last-of-type text").clone() // y-axis unit label
.attr("x", -2)
.attr("text-anchor", "start")
.attr("class", "xsmall-copy font-bold")
.text(data.y))
Insert cell
line = d3.line()
.defined(d => !isNaN(d.value))
.x(d => x(d.date))
.y(d => y(d.value))
Insert cell
data = Object.assign((await d3.csv("https://gist.githubusercontent.com/mbostock/14613fb82f32f40119009c94f5a46d72/raw/d0d70ffb7b749714e4ba1dece761f6502b2bdea2/aapl.csv", d3.autoType)).map(({date, close}) => ({date, value: close})), {y: "$ Close"})
Insert cell
data.y
Insert cell
d3 = require("d3@5")
Insert cell
md`---
## Styles`
Insert cell
html`<link rel="stylesheet" type="text/css" href="https://cdn.openai.com/miscellaneous/observable-1.5.0/styles/openai-css.css">`
Insert cell
html`<style>
svg, g {
color: var(--black);
font-size: 1rem;
}
#chart .line {
stroke: var(--light-green);
}
</style>`
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