Published
Edited
Sep 29, 2019
Insert cell
Insert cell
d3 = require("d3@5");
Insert cell
Insert cell
carData = fetch("https://vega.github.io/editor/data/cars.json")
.then(result => result.json());
Insert cell
Insert cell
aggregatedDimension = "Horsepower"
Insert cell
Insert cell
d3ArrayFunctions = require("d3-array@^2.2") // read more at https://github.com/d3/d3-array
Insert cell
groupedByYears = d3ArrayFunctions.group(carData, d => d.Year);
Insert cell
meanDimensionGroupedByYears = {
const meanDimensionGroupedByYears = {};
for (let [year, cars] of groupedByYears) {
const meanForThatYear = d3ArrayFunctions.mean(cars, d => d[aggregatedDimension]);
meanDimensionGroupedByYears[year] = meanForThatYear;
}
yield meanDimensionGroupedByYears;
}
Insert cell
Insert cell
svg`
<svg id="canvas">
<g class="vis">
<g class="marks"></g>
<g class="axis x"></g>
<g class="axis y"></g>
</g>
</svg>
`
Insert cell
width = 1000
Insert cell
height = 500
Insert cell
margin = 25
Insert cell
canvas = d3.select("#canvas")
.attr("width", width)
.attr("height", height)
Insert cell
vis = canvas.select(".vis")
.attr("transform", `translate(${margin}, ${margin})`);
Insert cell
Insert cell
years = {
const yearIterator = groupedByYears.keys();
const years = [];
let hasNext = true;
while (hasNext) {
let nextYear = yearIterator.next();
hasNext = !nextYear.done;
if (hasNext) years.push(nextYear.value);
}
yield years;
}
Insert cell
// scaleX = ...
scaleX = d3.scaleBand()
.padding(0.1)
.domain(years)
.range([0, width - 2*margin]);
Insert cell
listOfMeanValues = Object.values(meanDimensionGroupedByYears);
Insert cell
// scaleY = ...
scaleY = d3.scaleLinear().domain([0, d3.max(listOfMeanValues)*1.1]).range([height - margin * 2, 0]);
Insert cell
Insert cell
// axisX = ...
axisX = d3.axisBottom(scaleX);
Insert cell
// axisY = ...
axisY = d3.axisLeft(scaleY);
Insert cell
// canvas.select(".axis.x").call(...)
// canvas.select...
canvas.select(".axis.x")
.attr("transform", `translate(0,${height - 2*margin})`)
.call(axisX);
Insert cell
canvas.select(".axis.y")
.call(axisY);
Insert cell
Insert cell
marks = canvas.select(".marks");
Insert cell
barMark = marks.selectAll("rect.bar").data(years)
.join("rect")
.attr("class", "bar")
.attr("x", d => scaleX(d))
.attr("y", d => scaleY(meanDimensionGroupedByYears[d]))
.attr("fill", "steelblue")
.attr("width", scaleX.bandwidth())
.attr("height", d => scaleY(0) - scaleY(meanDimensionGroupedByYears[d]))
Insert cell
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