Dumbbell Chart in R

Introduction

This may be the first post I have created solely to do with creating a chart in the R Statistics language. I have chosen to present a dumbbell chart for this page. My chart looks like this:

    



The Data


Let's understand the data, first of all and then we will see how to create the chart

What we see here are the GDP per Capita figures for four countries for two years: 2007 and 2021, as presented in the R code

ylabel <- c("UK","USA","Canada","Spain")
x2007 <- c(50653, 48050, 44640, 32591)
x2021 <- c(47334, 69287, 52051, 30116)

In case it's not clear: the UK data are 50653 for 2007 and 47334 for 2021

This is a very simple case and I always start from the simple and move towards the more complex. However, dumbbell charts thrive on the simple so there is nothing to worry about.

The Code


I used the ggplot2 package as the foundation of this chart but I also needed to install and/or load the following packages:

library(ggplot2)
library(ggalt)    
library(tidyverse)
library(scales)

The entire code is:

# Draw dumbbell plot

ggplot() +
  geom_dumbbell(data = datamain, aes(y = ylabel,
                                     x = x2007, 
                                     xend = x2021),
                size = 1.5, color = "blue", size_x = 7,
                size_xend = 7, colour_x = "red",
                colour_xend = "black")+
  scale_x_continuous(labels = comma)+ # make sure you load the scales package for this line
  labs(x="Value ($)",y="Country",
          title="GDP per Capita Over Time: UK, USA, Canada and Spain")+
  theme(axis.text=element_text(size=16),
        axis.title=element_text(size=16,face="bold"))+
  theme(panel.background = element_rect(fill = 'lightblue', color = 'black'),
        panel.grid.major = element_line(color = 'red', linetype = 'dotted', size=1),
        panel.grid.minor = element_line(color = 'grey', size = 1))

I have treble checked that this coding works as I think it should, including a cold reboot of my system and it works. What I mean it, you should be able just to copy and paste all of my code into RStudio and run it to obtain your dumbbell chart.

Do let me know if you have any problems, of course.

Exercise for you


Why not add the following data to your code in RStudio to see if your chart agrees with mine:

Individuals using the internet as % of population ... source: World Bank

ylabel <- c("Thailand","Malaysia","Singapore","Philippines","Cambodia","Laos PDR","Vietnam")
x2010 <- c(22,56,71,25,1,7,31)
x2021b <- c(78,90,92,50,33,34,70) # note for Cambodia this is 2017 data



Special Thanks


Kyle Walker was very helpful as I worked at creating dumbbell charts, so thanks to Kyle for that: twitter @kyle_e_walker


Duncan Williamson
21st September 2022

No comments: