Published
Edited
Dec 1, 2021
Insert cell
Insert cell
Insert cell
Insert cell
viewof table = Inputs.table(trash, {})
Insert cell
Insert cell
Insert cell
//here I define the border of my graph. 10px on top and on the bottom, 50px on the left & right
margin = ({ top: 50, right: 50, bottom: 50, left: 50 })
Insert cell
width = 1100 //width of the chart
Insert cell
height = 400 //height of the chart
Insert cell
Insert cell
x = d3
.scaleBand() //make a scale using band
.domain(trash.map((d) => d.category)) //use categories of my dataset
//.range([0,width])
.range([margin.left, width - margin.right]) //use my width, minus the margin (border)
.padding(0.1) //small space between bars
.round(true)
Insert cell
x.bandwidth()
Insert cell
y = d3
.scaleLinear() //use a linear scale
.domain([0, d3.max(trash, (d) => d.count)]) //use count values of my dataset
//.range([height,0])
.range([height - margin.top, margin.bottom]) //use my height, minus the margin
Insert cell
Insert cell
Insert cell
chart = {
const svg = d3.select(DOM.svg(width, height));

//bars
svg
.append("g")
.selectAll("rect")
.data(trash, (d) => d.id) //each datapoint should have a rectangle
.enter() //access data points, which do not have a bar yet
.append("rect") //append a rectangle for the dataset
.attr("x", (d) => x(d.category))
.attr("y", (d) => y(d.count))
.attr("width", x.bandwidth())
.attr("height", (d) => height - y(d.count) - margin.bottom)
.attr("fill", "steelblue");

//y labels (counts)
svg
.append("g")
.attr("transform", `translate(${margin.left},0)`) //transform the y scale by the margin
.call(d3.axisLeft(y).ticks(height / 40)) //create an axis with ticks
.call((g) => g.select(".domain").remove()) // use domain
.attr("font-family", "Helvetica"); //set font family

//x labels (categories)
svg
.append("g")
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x))
.call((g) => g.select(".domain").remove())
.attr("font-family", "Helvetica Neue");

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