Public
Edited
Aug 29, 2023
4 forks
Importers
13 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
data = [
{ year: 2005, value: 734.69 },
{ year: 2006, value: 750.70 },
{ year: 2007, value: 755.13 },
{ year: 2008, value: 694.19 },
{ year: 2009, value: 681.83 },
{ year: 2010, value: 718.98 },
{ year: 2011, value: 740.57 },
{ year: 2012, value: 752.24 },
{ year: 2013, value: 767.24 },
{ year: 2014, value: 802.45 },
{ year: 2015, value: 805.65 },
{ year: 2016, value: 935.58 },
{ year: 2017, value: 967.13 },
{ year: 2018, value: 1007.24 },
]

// Average spending per US Black Friday shopper by year
// source: https://www.thebalance.com/what-is-black-friday-3305710
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
yMax = d3.max(data, d => d.value)
Insert cell
Insert cell
xDomain = data.map(d => d.year)
Insert cell
xScale = d3.scaleBand()
.domain( xDomain )
.range([ margin.left, width - margin.right - margin.left ])
.padding(0.5)
Insert cell
Insert cell
yScale = d3.scaleLinear()
.domain([ 0, yMax ])
.range([ height - margin.bottom, margin.top ])
Insert cell
Insert cell
xAxis = d3.axisBottom(xScale)
.tickSizeOuter(0)
Insert cell
yAxis = d3.axisLeft(yScale)
.tickSizeOuter(0)
Insert cell
Insert cell
bars = {
const container = html `<svg width="900" height="500"/>`
const svg = d3.select(container)
svg.append('g')
.attr('class', 'bars')
.selectAll('rect')
.data( data )
.join('rect')
.attr('class', 'bar')
.attr('x', d => xScale(d.year))
.attr('y', d => yScale(d.value))
// bandwidth is a special function of scaleBand
// it returns the width of the band (bar) based on the configuration
// we set up earlier
.attr('width', xScale.bandwidth())
// remember that yScale(0) is the height of the entire chart
// so we subtract the y position of the top of the bar yScale(d.value)
// from it to get the total height of the bar.
.attr('height', d => yScale(0) - yScale(d.value))
.style('fill', '#7472c0')
// Here we render the x axis
svg.append('g')
.attr('class', 'x-axis')
// First set its container's (g) position to the
// bottom of the chart
.attr('transform', `translate(0,${ height - margin.bottom })`)
// then just call this to render it
.call( xAxis )

// it works the same for the y axis
svg.append('g')
.attr('class', 'y-axis')
.attr('transform', `translate(${ margin.left },0)`)
.call( yAxis )
return container
}
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require('d3@6')
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more