Axes and a complete bar chart

Learn the margin convention and axis rendering, and combine them with scales to build a complete bar chart.

🎯 Introduction

Bars alone are not enough: axis ticks tell readers what their heights mean. This article introduces D3's margin convention and shows how to generate an axis with one line of code, then combine everything into a complete bar chart.


🧱 The margin convention: make room for axes

Where should y-axis labels such as 0, 50, and 100 go? To the left of the plotting area. If bars start at the SVG's left edge, these labels are pushed outside the drawing surface.

The standard D3 approach is the margin convention: leave margins around the SVG and draw chart content in the central plotting area:

┌──────────────────────── svg ────────────────────────┐
│                    margin.top                        │
│         ┌───────────────────────────┐                │
│  margin │                           │  margin.right  │
│  .left  │     Plotting area (g)      │                │
│         │                           │                │
│         └───────────────────────────┘                │
│                   margin.bottom                      │
└──────────────────────────────────────────────────────┘

The implementation follows a consistent pattern: calculate the plotting width and height, append a g, and translate it to the plotting area's top-left corner. Draw all graphics inside this group:

const margin = { top: 20, right: 20, bottom: 30, left: 40 };
const width = 480 - margin.left - margin.right; // Plotting width: 420
const height = 280 - margin.top - margin.bottom; // Plotting height: 230

const svg = d3
    .select(svgRef.value)
    .append('g')
    .attr('transform', `translate(${margin.left}, ${margin.top})`);

Scale ranges now use width and height, and (0, 0) is the plotting area's top-left corner. The margins no longer affect your drawing calculations.

Compare the results: margins leave room for all tick labels, while removing them clips the axes at the SVG edges:

Blue area = margin. Dashed box = plotting area.

🧱 Draw an axis with one line

An axis contains a baseline, tick marks, and labels. Instead of drawing them individually, use D3's axis generators. Two common ones are:

  • d3.axisBottom(xScale): An x axis with ticks facing downward.
  • d3.axisLeft(yScale): A y axis with ticks facing left.

The pattern is append a g, translate it into position, and call the axis generator:

// Place the x axis at the bottom of the plotting area
svg.append('g').attr('transform', `translate(0, ${height})`).call(d3.axisBottom(xScale));

// Place the y axis on the left; the group is already at the top-left
svg.append('g').call(d3.axisLeft(yScale));

call passes the current g selection to the axis generator. D3 then creates child elements inside it, roughly as follows:

g (axis)
├── Baseline (a horizontal line)
├── Tick group 1: short line + label "Mon"
├── Tick group 2: short line + label "Tue"
└── ……

└── …

The scale determines tick positions and values automatically. This is how scales and axes work together.


Try the button: it runs call(d3.axisBottom(xScale)) and generates the axis immediately:

🧱 Customize ticks

d3.axisLeft(yScale)
You can also configure the generated axis:
    .ticks(5) // Request approximately five ticks
.tickFormat((d) => `${d} units`); // Add a unit to each label
  • .ticks(5) requests roughly five ticks; D3 chooses a convenient interval.
  • .tickFormat() customizes tick labels, for example by adding units.

Compare the default and customized ticks:

🛠 A complete bar chart

views/BarChart.vue
<template>
    <svg ref="svgRef" class="chart"></svg>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import * as d3 from 'd3';

const svgRef = ref(null);

const data = [
Combine margins, scales, axes, and data binding:
    { day: 'Mon', value: 120 },
    { day: 'Tue', value: 200 },
    { day: 'Wed', value: 150 },
    { day: 'Thu', value: 80 },
];

onMounted(() => {
    const margin = { top: 20, right: 20, bottom: 30, left: 40 };
    const width = 480 - margin.left - margin.right;
    const height = 280 - margin.top - margin.bottom;

    const svg = d3
        .select(svgRef.value)
        .append('g')
        .attr('transform', `translate(${margin.left}, ${margin.top})`);

    { day: 'Fri', value: 70 },
    const xScale = d3
        .scaleBand()
        .domain(data.map((d) => d.day))
        .range([0, width])
        .padding(0.2);

    // Categorical x scale
    const yScale = d3
        .scaleLinear()
        .domain([0, d3.max(data, (d) => d.value)])
        .range([height, 0])
        .nice();

    // Numeric y scale
    svg.selectAll('rect')
        .data(data)
        .join('rect')
        .attr('x', (d) => xScale(d.day))
        .attr('y', (d) => yScale(d.value))
        .attr('width', xScale.bandwidth())
        .attr('height', (d) => height - yScale(d.value))
        .attr('fill', '#5470c6');

    // Draw bars
    svg.append('g')
        .attr('transform', `translate(0, ${height})`)
        .call(d3.axisBottom(xScale));

    svg.append('g').call(d3.axisLeft(yScale));
});
</script>

<style scoped>
.chart {
    width: 480px;
    height: 280px;
}
</style>

Note the two bar attributes: yScale(d.value) gives the bar's top position, while height - yScale(d.value) subtracts that position from the plotting height to obtain the bar's height.

Each geometric attribute now comes from a scale, allowing the chart to adapt to different data. That is what makes this a complete chart rather than a minimal example.

Here is the rendered result:


❓ Questions and answers

Q1: How can I fix overlapping tick labels?

Three common approaches are reducing the tick count, shortening labels with tickFormat (for example, displaying 1000 as 1k), or rotating labels.

Q2: How do I draw a horizontal bar chart?

Swap the scales: use scaleLinear on x and scaleBand on y, and represent values with bar width.

Q3: Why use call to draw an axis?

Rendering an axis creates a baseline, tick marks, labels, and more. call delegates these operations to the generator within a method chain, keeping the code concise. It is the idiomatic D3 approach.

Q4: How should I choose margin values?

Use label length as a guide. Increase left for large numbers such as 1000000, and increase bottom for rotated x-axis labels. There is no fixed rule; adjust while inspecting the chart.


🧪 Exercise

Turn the complete bar chart into a chart of scores for three subjects:

  1. Use Chinese: 80, Math: 95, and English: 88.
  2. Set .ticks(5) on the y axis and use tickFormat to append “points” to each label.
  3. Change the bar color to #ee6666.
const data = [
    { subject: 'Chinese', score: 80 },
    { subject: 'Math', score: 95 },
    { subject: 'English', score: 88 },
];

onMounted(() => {
    // Write your code here
});

🎉 You can now draw a complete chart with axes! Next, shape generators will take us into line charts and pie charts.