Published
Edited
Nov 14, 2020
Importers
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function normalize_values(data) {
return data.map(({ abv, ibu, ph }) => ({
abv: abv < 0 || abv > 25 ? null : abv,
ibu: abv < 0 || ibu > 350 ? null : ibu,
ph: ph < 0 || ph > 14 ? null : ph
}));
}
Insert cell
normalized_beers = normalize_values(fetched_beers)
Insert cell
Insert cell
Insert cell
x = d3
.scaleLinear()
.domain(d3.extent(normalized_beers, d => d.abv))
.nice()
.range([margin.left, width - margin.right])
Insert cell
xAxis = g =>
g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(
d3
.axisBottom(x)
.tickSize(-(height - margin.top - margin.bottom))
.ticks((10 * width) / height)
)
.call(g => g.select(".domain").remove())
Insert cell
y = d3
.scaleLinear()
.domain(d3.extent(normalized_beers, d => d.ibu))
.nice()
.range([height - margin.bottom, margin.top])
Insert cell
yAxis = g =>
g
.attr("transform", `translate(${margin.left},0)`)
.call(
d3
.axisLeft(y)
.tickSize(-(width + margin.left + margin.right))
.ticks((10 * height) / width)
)
.call(g => g.select(".domain").remove())
Insert cell
fill = d3
.scaleSequential()
.domain(d3.extent(normalized_beers, d => d.ph))
.interpolator(d3.interpolateViridis)
Insert cell
function plot_scatter(data) {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);
const set_font_primary = node => node.attr("font-family", "Arial Narrow");

const add_tspan = (text, string) =>
text
.append("tspan")
.text(string)
.attr("style", "display: block");

svg
.append("text")
.call(set_font_primary)
.attr("x", margin.left)
.attr("y", margin.top / 3)
.call(
add_tspan,
"Alcohol content, bitterness, and acidity of beers from the Punk API"
);

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

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

svg
.append("g")
.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d => x(d.abv))
.attr("cy", d => y(d.ibu))
.attr("r", 3)
.attr("fill", d => fill(d.ph));

// X axis label:
svg
.append("text")
.call(set_font_primary)
.attr("text-anchor", "end")
.attr("x", width)
.attr("y", height - margin.top / 3)
.text("ABV");

// Y axis label:
svg
.append("text")
.call(set_font_primary)
.attr("text-anchor", "end")
.attr("transform", "rotate(-90)")
.attr("y", margin.left / 3)
.attr("x", -margin.top)
.text("IBU");

// Remove first tick lines for each axis
svg.selectAll(".tick:first-child line").attr("stroke", "#ffffff");
svg.selectAll(".tick:not(:first-child) line").attr("stroke", "#ebebeb");

return svg.node();
}
Insert cell
Insert cell
plot_scatter(normalized_beers)
Insert cell
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