Data Visualization using GGPlot2

GGPlot Barplot

Barplot (also known as Bar Graph or Column Graph) is used to show discrete, numerical comparisons across categories. One axis of the chart shows the specific categories being compared and the other axis represents a discrete value scale.

This article describes how to create a barplot using the ggplot2 R package.

You will learn how to:

  • Create basic and grouped barplots
  • Add labels to a barplot
  • Change the bar line and fill colors by group

Contents:

Related Book

GGPlot2 Essentials for Great Data Visualization in R

Key R functions

  • Key function: geom_col() for creating bar plots. The heights of the bars represent values in the data.
  • Key arguments to customize the plot:
    • color, fill: bar border and fill color
    • width: bar width

Data preparation

We’ll create two data frames derived from the ToothGrowth datasets.

df <- data.frame(dose=c("D0.5", "D1", "D2"),
                len=c(4.2, 10, 29.5))

head(df)
##   dose  len
## 1 D0.5  4.2
## 2   D1 10.0
## 3   D2 29.5
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
                dose=rep(c("D0.5", "D1", "D2"),2),
                len=c(6.8, 15, 33, 4.2, 10, 29.5))

head(df2)
##   supp dose  len
## 1   VC D0.5  6.8
## 2   VC   D1 15.0
## 3   VC   D2 33.0
## 4   OJ D0.5  4.2
## 5   OJ   D1 10.0
## 6   OJ   D2 29.5
  • len: Tooth length
  • dose: Dose in milligrams (0.5, 1, 2)
  • supp: Supplement type (VC or OJ)

Loading required R package

Load the ggplot2 package and set the default theme to theme_classic() with the legend at the top of the plot:

library(ggplot2)
theme_set(
  theme_classic() +
    theme(legend.position = "top")
  )

Basic barplots

We start by creating a simple barplot (named f) using the df data set:

f <- ggplot(df, aes(x = dose, y = len))
# Basic bar plot
f + geom_col()

# Change fill color and add labels at the top (vjust = -0.3)
f + geom_col(fill = "#0073C2FF") +
  geom_text(aes(label = len), vjust = -0.3)
   
# Label inside bars, vjust = 1.6
f + geom_col(fill = "#0073C2FF")+
  geom_text(aes(label = len), vjust = 1.6, color = "white")

Note that, it’s possible to change the width of bars using the argument width (e.g.: width = 0.5)

Change barplot colors by groups

We’ll change the barplot line and fill color by the variable dose group levels. To set a palette of custom color the function scale_color_manual() is used.

# Change barplot line colors by groups
f + geom_col(aes(color = dose), fill = "white") +
  scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"))

# Change barplot fill colors by groups
f + geom_col(aes(fill = dose)) +
  scale_fill_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"))

Barplot with multiple groups

Create stacked and dodged bar plots. Use the functions scale_color_manual() and scale_fill_manual() to set manually the bars border line colors and area fill colors.

# Stacked bar plots of y = counts by x = cut,
# colored by the variable color
ggplot(df2, aes(x = dose, y = len)) +
  geom_col(aes(color = supp, fill = supp), position = position_stack()) +
  scale_color_manual(values = c("#0073C2FF", "#EFC000FF"))+
  scale_fill_manual(values = c("#0073C2FF", "#EFC000FF"))

# Use position = position_dodge() 
p <- ggplot(df2, aes(x = dose, y = len)) +
  geom_col(aes(color = supp, fill = supp), position = position_dodge(0.8), width = 0.7) +
  scale_color_manual(values = c("#0073C2FF", "#EFC000FF"))+
  scale_fill_manual(values = c("#0073C2FF", "#EFC000FF"))
p

Note that, position_stack() automatically stack values in reverse order of the group aesthetic. This default ensures that bar colors align with the default legend. You can change this behavior by using position = position_stack(reverse = TRUE).

Add labels to a dodged barplot:

p + geom_text(
  aes(label = len, group = supp), 
  position = position_dodge(0.8),
  vjust = -0.3, size = 3.5
)

Add labels to a stacked bar plots. 4 steps required to compute the position of text labels:

  • Group the data by the dose variable
  • Sort the data by dose and supp columns. As position_stack() reverse the group order, supp column should be sorted in descending order.
  • Calculate the cumulative sum of len for each dose category. Used as the y coordinates of labels. To put the label in the middle of the bars, we’ll use cumsum(len) - 0.5 * len.
  • Create the bar graph and add labels
# Arrange/sort and compute cumulative summs
library(dplyr)
 df2 <- df2 %>%
  group_by(dose) %>%
  arrange(dose, desc(supp)) %>%
  mutate(lab_ypos = cumsum(len) - 0.5 * len) 
df2
## # A tibble: 6 x 4
## # Groups:   dose [3]
##   supp  dose    len lab_ypos
##   <fct> <fct> <dbl>    <dbl>
## 1 VC    D0.5    6.8      3.4
## 2 OJ    D0.5    4.2      8.9
## 3 VC    D1     15        7.5
## 4 OJ    D1     10       20  
## 5 VC    D2     33       16.5
## 6 OJ    D2     29.5     47.8
# Create stacked bar graphs with labels
ggplot(data = df2, aes(x = dose, y = len)) +
  geom_col(aes(fill = supp), width = 0.7)+
  geom_text(aes(y = lab_ypos, label = len, group =supp), color = "white") +
  scale_color_manual(values = c("#0073C2FF", "#EFC000FF"))+
  scale_fill_manual(values = c("#0073C2FF", "#EFC000FF"))

Conclusion

This article describes how to create and customize barplot using the ggplot2 R package.

Version: Français

GGPlot Line Plot (Prev Lesson)
(Next Lesson) GGPlot Error Bars
Back to Data Visualization using GGPlot2

No Comments

Give a comment

Teacher
Alboukadel Kassambara
Role : Founder of Datanovia
Read More