Margin and translation


Most of the chart types use a bottom and a left axis.

In that case, there is a need to leave some space for the tick label and axis titles. Let's see how to implement this.

Wip
4 minutes read

Chart area and Bounds area

The bottom and left axes are not displays at the border of the main chart component. Some margins are computed by the viz component. It is important to understand that a chart is composed by:

  • the global chart area, often specified by the width and height properties of the chart components.
  • the "bounds" area, i.e. the area located inside the x and y axis. It is calculated by substracting the margins

Implementation

Let's start by defining the margins we want to use, as a const. This can be defined at the top of your file, out of the viz component, or even in a separate file containing all your constants.

const MARGIN = {
  top: 10,
  right: 30,
  bottom: 50,
  left: 30
}

Then we can compute, at the beginning of the viz component, the dimension of the boundWidth and boundHeight

const boundsWidth = width - MARGIN.right - MARGIN.left;
const boundsHeight = height - MARGIN.top - MARGIN.bottom;

And finally the svg is going to be rendered like this:

<svg width={width} height={height}>
  <g
    width={boundsWidth}
    height={boundsHeight}
    transform={"translate(" + MARGIN.left + " , " + MARGIN.top].join(',')})"}
  >
    // ... all shapes go here
  </g>
</svg>

Explain the translation

Explain that for the bottom axis, an additional translation is required to draw it at the bottom

Draw the axis

Now that we have some space for it, it is time to actually draw the axis. Let's build a reusable component.