Public
Edited
Jan 26, 2023
1 fork
2 stars
Insert cell
Insert cell
Insert cell
fruits = [
{ name: "🍊", count: 21 },
{ name: "🍇", count: 13 },
{ name: "🍏", count: 8 },
{ name: "🍌", count: 5 },
{ name: "🍐", count: 3 },
{ name: "🍋", count: 2 },
{ name: "🍎", count: 1 },
{ name: "🍉", count: 1 }
]
Insert cell
Insert cell
xScale = d3
.scaleBand()
.domain(d3.range(fruits.length))
.range([margin.left, width - margin.right])
.padding(0.1)
Insert cell
yScale = d3
.scaleLinear()
.domain([0, d3.max(fruits, (d) => d.count)])
.nice()
.range([height - margin.bottom, margin.top])
Insert cell
Insert cell
xAxis = (g) =>
g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(xScale).tickFormat((i) => fruits[i].name))
Insert cell
yAxis = (g) =>
g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(yScale))
Insert cell
Insert cell
chart = {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);

svg
.append("g")
.selectAll("rect")
.data(fruits)
.join("rect")
.attr("fill", "steelblue")
.attr("x", (d, i) => xScale(i))
.attr("y", (d) => yScale(d.count))
.attr("height", (d) => yScale(0) - yScale(d.count))
.attr("width", xScale.bandwidth());

svg.append("g").call(xAxis);

svg.append("g").call(yAxis);

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