d3(2) Bar Charts

Scales

  • Domain & Range: Input & Output

  • Scale

    1
    2
    3
    const y = d3.scaleLinear();
    .domain([0, 1000])
    .range([0, 500])

    To use this scale

    1
    .attr('height', d => y(d.orders))
  • Band scales - scales on x coordinate

    1
    2
    3
    4
    5
    6
    const x = d3.scaleBand()
    .domain(data.map(item => item.name)) // an array of 'names'
    .range([0, 500])

    x('A name') // the parameter should be a value in the previous array
    x.bandwidth() // return the width of each bar (same)

    To use the bandwidth

    1
    2
    rects.attr('width', x.bandwidth) // the width of each bar
    .attr('x', d => x(d.name)) // seperate each bar

    To add ‘paddings’ between bars

    1
    2
    3
    4
    5
    const x = d3.scaleBand()
    .domain(data.map(item => item.name)) // an array of 'names'
    .range([0, 500])
    .paddingInner(0.2)
    .paddingOuter(0.2)
  • If the input exceeds the domain - Min, Max & Extent

    1
    2
    3
    4
    const min = d3.min(data, d => d.orders)
    const max = d3.max(data, d => d.orders)

    const extent = d3.extent(data, d => d.orders) // find both min & max
  • Margins & Groups

    1
    2
    3
    4
    5
    6
    7
    8
    const margin = {top: 20, right: 20, bottom: 100, left: 100}
    const graphWidth = 600 - margin.left - margin.right;
    const graphHeight = 600 - margin.top - margin.bottom;

    const graph = svg.append('g')
    .attr('width', graphWidth)
    .attr('height', graphHeight)
    .attr('transform', `translate(${margin.left},${margin.top})`)
  • Axis

    1
    2
    3
    4
    5
    6
    7
    8
    9
    const xAxisGroup = graph.append('g');
    .attr('transform', `translate(0, ${graphHeight})`); // shift the axis to the bottom
    const yAxisGroup = graph.append('g');

    const xAxies = d3.axisBottom(x);
    const yAxies = d3.axisLeft(y);

    xAxisGroup.call(xAxis);
    yAxisGroup.call(yAxis);
  • Invert the bar chart

    1. Switch the direction of output

      1
      2
      3
      4
      5
      6
      7
      8
      const y = d3.scaleLinear()
      .domain([0, d3.max(data, d => d.orders)])
      .range([graphHeight, 0]); // switch the order

      // ... down below
      rects.enter()
      .append('rect')
      .attr('height', d => graphHeight - y(d.orders));
    2. Change each bar’s starting position

      1
      2
      3
      4
      5
      6
      // rects.attr()

      rects.enter()
      .append('rect')
      //...
      .attr('y', d => y(d.orders))
  • Tick formatting

    1
    2
    3
    4
    5
    6
    7
    8
    const yAxis = d3.axisLeft(y)
    .ticks(5) // how many ticks (not exactly) will be displayed
    .tickFormat(d => d + ' orders');

    // To rotate the x axis ticks
    xAxisGroup.selectAll('text')
    .attr('transform', 'rotate(-40)')
    .attr('text-anchor', 'end');