Code

D3.js

Bar Chart

Beginner Vertical bar chart using scaleBand for categories, scaleLinear for values, and axisBottom / axisLeft. d3-scale

const x = d3.scaleBand()
  .domain(data.map(d => d.label))
  .range([0, innerWidth])
  .padding(0.2);

const y = d3.scaleLinear()
  .domain([0, 100])
  .range([innerHeight, 0]);

// Bars
g.selectAll('rect')
  .data(data)
  .join('rect')
  .attr('x', d => x(d.label))
  .attr('y', d => y(d.value))
  .attr('width',  x.bandwidth())
  .attr('height', d => innerHeight - y(d.value))
  .attr('fill', '#4f46e5')
  .attr('rx', 3);

// Axes
g.append('g')
  .attr('transform', `translate(0,${innerHeight})`)
  .call(d3.axisBottom(x));

g.append('g')
  .call(d3.axisLeft(y).ticks(5));
Key APIs
  • d3.scaleBand() — ordinal scale with configurable padding for bar charts
  • d3.scaleLinear() — continuous numeric scale
  • scale.bandwidth() — the computed width of each band
  • d3.axisBottom(scale) / d3.axisLeft(scale) — axis generators
  • g.call(axis) — renders the axis into a <g> element