Published
Edited
Nov 9, 2021
Insert cell
Insert cell
Insert cell
# Bar Chart
Insert cell
dataset = d3.range(10).map((d) => ({
name: "James Mary Robert Patricia John Jennifer Michael Linda William Elizabeth".split(
" "
)[d],
scoreA: d3.randomInt(0, 100)(),
scoreB: d3.randomInt(0, 100)()
}))
Insert cell
Inputs.table(dataset)
Insert cell
chart = {
const width = 600;
const height = 300;
const margin = { top: 20, right: 50, bottom: 10, left: 50 };
const svg = d3
.create("svg")
.attr("viewBox", [0, 0, width, height])
.attr("width", width);
const x = d3
.scaleLinear()
.domain([0, d3.max(dataset, (d) => d.scoreA)])
.range([margin.left, width - margin.right]);
const y = d3
.scaleBand()
.domain(dataset.map((d) => d.name))
.range([margin.top, height - margin.bottom])
.padding(0.1);

const xAxis = d3.axisTop(x);
const yAxis = d3.axisLeft(y);

svg
.selectAll("rect")
.data(dataset)
.join("rect")
.attr("x", x(0))
.attr("y", (d) => y(d.name))
.attr("width", (d) => x(d.scoreA) - x(0))
.attr("height", y.bandwidth())
.attr("fill", "orange");

svg
.selectAll("text.label")
.data(dataset)
.join("text")
.attr("class", "label")
.attr("x", (d) => x(d.scoreA))
.attr("y", (d) => y(d.name) + y.bandwidth())
.attr("dy", "-0.4em")
.attr("dx", "0.5em")
.text((d) => d.scoreA);

svg.append("g").attr("transform", `translate(0, ${margin.top})`).call(xAxis);
svg.append("g").attr("transform", `translate(${margin.left}, 0)`).call(yAxis);

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