Published
Edited
Dec 12, 2020
2 forks
2 stars
Insert cell
md`# Week 1: Cupcake Barchart
Project from MICA D3 workshop, week 1.`
Insert cell
chart = {
const svg = d3
.create('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom);

const g = svg
.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);

g.append('g').call(d3.axisLeft(y));

g.append('g')
.attr('transform', `translate(0, ${height})`) //move x axis to the bottom
.call(d3.axisBottom(x))
.selectAll('text')
.attr('x', x.bandwidth() / 2)
.attr('y', 0)
.attr('dy', '.35em')
.attr('transform', 'rotate(90)')
.attr('text-anchor', 'start');

let bar = g
.selectAll('.bar')
.data(results)
.enter()
.append('g')
.attr('class', 'bar-group');

bar
.append('rect')
.attr('class', '.bar')
.attr('x', d => x(d.flavors))
.attr('y', d => y(d.sales))
.attr('width', x.bandwidth())
.attr('height', d => height - y(d.sales))
.style('fill', 'steelblue');

bar
.append('text')
.text(d => d.sales)
.attr('x', d => x(d.flavors) + x.bandwidth() / 2)
.attr('y', d => y(d.sales) + 15)
.attr('text-anchor', 'middle')
.style('font-family', 'sans-serif')
.style('font-size', 12)
.style('fill', 'white');

return svg.node();
}
Insert cell
x = d3
.scaleBand()
.domain(results.map(d => d.flavors))
.range([0, width])
.padding(0.1)
Insert cell
y = d3
.scaleLinear()
.domain([0, d3.max(results, d => d.sales)])
.range([height, 0])
Insert cell
Insert cell
Insert cell
Insert cell
results = Object.assign(
d3.csvParse(
await FileAttachment('sales.csv').text(),
({ flavors, sales }) => ({ flavors: flavors, sales: +sales })
)
)
Insert cell
d3 = require("d3@6")
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