Here is the YouTube Video link for this tutuorial.

Video link https://youtu.be/rLk32vjetxQ

Side by Side bar charts in GGPLOT

Audience

For beginners or experienced R users wanting to learn GGPLOT charting techniques.

Packages used

library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.1.3
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.1.3

Sample dataset.

Let us create some data. We will create some sample data from the mpg dataset which comes with the ggplto2 package.

We will also create a colour palette of six colours to use in colouring the bars.

df <- ggplot2::mpg%>%
  dplyr::group_by(manufacturer,class)%>%
  dplyr::tally()

# Also create a colour palette
mypalette <- c('#6A3CAB','#BC8CFF' ,'#A86FF7'
               ,'#ABA72B','#C045C4', '#F7F46F','#917C91')

First Chart

This chart is a stacked bar chart.

# First Chart
pl1 <- ggplot(data = df, aes(x = manufacturer, y =n, fill = class))
pl1 <- pl1 + geom_bar(stat ="identity")
pl1 <- pl1 + theme_bw()
pl1 <- pl1 + scale_fill_manual(values = mypalette)
pl1

Second Chart

We will attempt to create a side by side bar chart using the position_dodge option. But you can see that the bar widths seem to vary, depending on the data. Some car manufacturers have 1, 2 ,3 or 4 car classes. And if a manufactur has only 1 class of car available, then the single bar tends to occupy the whole of the available space. So the width of the bar is big compared to other manufacturers who have 2,3 or 4 car classes. This is bit annoying.

# Second Chart - side by side
pl2 <- ggplot(data = df, aes(x = manufacturer, y =n, fill = class))
pl2 <- pl2 + geom_bar(stat ="identity", position=position_dodge())
pl2 <- pl2 + theme_bw()
pl2 <- pl2 + scale_fill_manual(values = mypalette)
pl2

Side by Side bar chart

Let us fix the issue which we faced in the previous chart. Using the preserve = ‘single’ option we can preserve the widths of the bars, to make them uniform.

# third chart
pl3 <- ggplot(data = df, aes(x = manufacturer, y =n, fill = class))
pl3 <- pl3 + geom_bar(stat ="identity"
                    , position=position_dodge(preserve = "single"))
pl3 <- pl3 + theme_bw()
pl3 <- pl3 + scale_fill_manual(values = mypalette)
pl3