Published
Edited
May 24, 2019
1 star
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require("d3@5")
Insert cell
freedom = d3.csv("https://gist.githubusercontent.com/will-r-chase/3f4503ccfe9d7a559023ce62cfafbe6c/raw/b45c9cc5b512a36f7a4ae2755b03a6acb39be489/human_freedom_index_2018.csv", d3.autoType)
Insert cell
Insert cell
chart = {
//yes I know it's wrong to use a bar chart for a date x-axis
//im just practicing, maybe it's a bad idea but whatevs
const svg = d3.select(DOM.svg(width, height));
//bars
svg.append("g")
.selectAll("rect")
.data(year_means)
.join("rect")
.attr("x", d => scale_x(d.key))
.attr("width", scale_x.bandwidth())
.attr("y", d => scale_y(d.value))
.attr("height", d => scale_y(0) - scale_y(d.value))
.attr("fill", "steelblue");
//text labels for bars
svg.append("g")
.attr("fill", "black")
.attr("text-anchor", "middle")
.selectAll("text")
.data(year_means)
.join("text")
.attr("x", d => scale_x(d.key) + scale_x.bandwidth()/2)
.attr("y", d => scale_y(d.value) - 5)
.text(d => format(d.value));
//x axis
svg.append("g")
.call(xAxis)
.style("font-size", "14px");
//y axis
svg.append("g")
.call(yAxis)
.style("font-size", "14px");
//x axis label
svg.append("text")
.attr("transform", "translate(" + (width/2) + "," + (height - 20) + ")")
.style("text-anchor", "middle")
.style("font-size", "20px")
.text("Date");
//y axis label
svg.append("text")
.attr("transform", "translate(" + (margin.left/3) + "," + (height/2) + ")rotate(-90)")
.style("text-anchor", "middle")
.style("font-size", "20px")
.text("Personal freedom score");
//title
svg.append("text")
.attr("transform", "translate(0," + margin.top/3 + ")")
.style("text-anchor", "left")
.style("font-size", "25px")
.text("Worldwide average personal freedom score, 2008 - 2016")
return svg.node();
}
Insert cell
format = d3.format(".2f")
Insert cell
xAxis = g => g
.attr("transform", `translate(0, ${height - margin.bottom})`)
.call(d3.axisBottom(scale_x).tickSizeOuter(0))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left}, 0)`)
.call(d3.axisLeft(scale_y).tickSizeOuter(0))
Insert cell
height = 500
Insert cell
width = 800
Insert cell
margin = ({top: 100, right: 20, bottom: 70, left: 50})
Insert cell
scale_y = d3.scaleLinear()
.domain([0, d3.max(year_means.map(d => d.value))])
.range([height - margin.bottom, margin.top]);
Insert cell
scale_x = d3.scaleBand()
.domain(year_means.map(d => d.key))
.rangeRound([margin.left, width - margin.right])
.padding(0.1);
Insert cell
year_means = d3.nest()
.key(d => d.year)
.rollup(function(v) { return d3.mean(v, d => d.pf_score); })
.entries(freedom)
.reverse();
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