Published
Edited
May 13, 2020
Insert cell
md`# FreeCodeCamp D3 projects - bar chart`
Insert cell
root2 = html`
<style>
.bar:hover {
fill: white
}
</style>
<main></main>
`
Insert cell
{
const padding = 50
const width = 1000
const height = 500
const year = d3.timeFormat("%Y")
const quarter = d3.timeFormat("%Y Q%q")

const xScale = d3.scaleTime()
.domain([dataset[0][0], dataset[dataset.length - 1][0]])
.range([padding, width - padding])
const barWidth = (width - padding - padding) / dataset.length

const yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, ([_, GDP]) => GDP)])
.range([height - padding, padding])
const xAxis = d3.axisBottom(xScale)
const yAxis = d3.axisLeft(yScale)

const svg = d3.select(root2)
.append("svg")
.attr("width", width)
.attr("height", height)
svg.selectAll('rect')
.data(dataset).enter()
.append('rect')
.attr('fill', 'blue')
.attr('class', 'bar')
.attr('x', ([date, ]) => xScale(date))
.attr('y', ([, gdp]) => yScale(gdp))
.attr('height', ([, gdp]) => height -padding - yScale(gdp))
.attr('width', barWidth)
.append('title')
.text(([date, gdp]) => `${quarter(date)} -$${gdp}B`)
svg.append("g")
.attr("transform", `translate(0, ${height - padding})`)
.call(xAxis);
svg.append("g")
.attr("transform", `translate(${padding}, 0)`)
.call(yAxis);
svg.append('text')
.text('Federal Reserve Economic Data, Gross Domestic Product')
.attr("x", (width / 2))
.attr("y", 0 + (padding / 2))
.attr("text-anchor", "middle")
.style("font-size", "16px")
}
Insert cell
md`## Appendix`
Insert cell
d3 = require('d3')
Insert cell
fred = d3.json("https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json")
Insert cell
dataset = {
const parseDate = d3.utcParse("%Y-%m-%d")
return fred.data.map(([date, gdp]) => [parseDate(date), gdp])
}
Insert cell
d3.extent(dataset, d => d[0])
Insert cell
d3.extent(dataset, d => d[1])
Insert cell
year = d3.timeFormat("%Y")
Insert cell
year(dataset[0][0])
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