Gauge charts in R and Python

In this post, we will create a “Gauge Meter” chart by hacking the donut charts and shapes. Something like those speedometers in cars.

Outline

What are the basic components of speedometers?

A dial to represent the current speed (state), a semi-circular meter showing the speed range.

We will use donut charts with custom colors to create the semi-circular meter. To hide the lower portion of a donut chart, we will color it same as the background.

To create the dial, we will use the filled triangle shape.

Obstacle

There is one problem, we also need to show the tick marks representing the speed over the semi-circular meter.

By default, labels on a section of pie or donut charts are positioned at the center of the section. But we need them to indicate the start and end of sections.

To solve this, the semi-circular meter will be overlapped on a base donut chart to create the analog range of the meter. We will have to rotate the base chart to align the range marks in the edges of meter’s section.

We are using Python in the post, corresponding R code is available at the end of it.

Base Chart (rotated)

To make a gauge meter with 4 equally sized sections, we will create 5 sections in the base chart. So that center(position of the label) aligns with the edges of each section.

Outline of the generated base chart will look like the one below.

Base donut chart

Meter Chart

Now we will superimpose our semi-circular meter on top of this. For that, we will also use 5 sections, but one of them will be invisible to form the lower half (colored same as the background).

You can see that the first section’s value is equal to the sum of other sections. We are using rotation and direction parameters to start the sections from 3 o’clock [rotation=90] instead of the default value of 12 o’clock [rotation=0].

After imposing on the base chart, it’ll look like this.

meter chart

Dail

Now we need a dial to show the current position in the meter at a particular time.

Plotly’s path shape can be used for this. A nice explanation of SVG path is available here by Mozilla.

For the filled triangle, the first point (0.235, 0.5) is left to the center of the meter (0.24, 0.5), the second point (0.24 0.62) is representing the current position on the semi-circle and the third point (0.245, 0.5) is just right to the center.

M represents the ‘Move’ command that moves the cursor to a particular point, L is the ‘Line To’ command and Z represents the ‘Close Path’ command. This way, this path string makes a triangle with those three points.

Now we have our gauge meter representing the value of 50 out of 100.

If you want to use it in R, the code is available here.

Pravendra

Software Developer. Egalitarian Aesthete.