Public
Edited
Apr 11
Insert cell
Insert cell
data = [20, 30, 75]
Insert cell
chart = {
// Set the canvas dimensions
const canvasWidth = 570;
const canvasHeight = 360;

const svg = d3
.create("svg") // Create an SVG element
.attr("viewBox", `0 0 ${canvasWidth} ${canvasHeight}`)
.style("border", "1px solid black"); // For illustrative border

// Chart drawing dimensions
const chartWidth = canvasWidth - 30;
const chartHeight = canvasHeight - 40;

// Margins / starting points for the chart
const chartStartX = 25;
const chartStartY = 15;
// Define a discrete (band) scale for the x-axis
const scaleX = d3
.scaleBand()
.domain(d3.range(data.length))
.range([0, chartWidth])
.padding(0.05);

// Define a linear scale for the y-axis
const scaleY = d3
.scaleLinear()
.domain([0, d3.max(data)])
.range([chartHeight, 0]);

// Create a group for the chart elements
const chartGroup = svg
.append("g")
.attr("transform", `translate(${chartStartX}, ${chartStartY})`)
.attr("fill", "steelblue");

// Draw the bars
chartGroup
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", (d, i) => scaleX(i))
.attr("width", scaleX.bandwidth())
.attr("y", (d) => scaleY(d))
.attr("height", (d) => scaleY(0) - scaleY(d));

// Add a border around the chart area
chartGroup
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", chartWidth)
.attr("height", chartHeight)
.attr("fill", "none")
.attr("stroke", "black")
.attr("stroke-width", 1);

// Append the x-axis: shift by chartStartX and chartStartY plus chart height
svg
.append("g")
.attr("transform", `translate(${chartStartX}, ${chartStartY + chartHeight})`)
.call(d3.axisBottom(scaleX).tickFormat(i => i + 1));

// Append the y-axis: shift by chartStartX and chartStartY
svg
.append("g")
.attr("transform", `translate(${chartStartX}, ${chartStartY})`)
.call(d3.axisLeft(scaleY));

// Return the SVG node for Observable to render
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