Visualize data in R: ggplot2 package and more

Overview

Teaching: 20 min
Exercises: 30 min
Questions
  • How to plot data with ggplot2?

Objectives
  • Visuallize your data with ggplot2.

ggplot2 package

Compare to basic plots, ggplot2 package provides better visually appealing plots. ggplot2 package needs to be installed before use.

Install

click on Packages tab, select on Install, then search ggplo2 under Packages to install ggplots2.

Screenshot of main code listing

Useful Resources

Points

library(ggplot2)
mp <- ggplot(xd, aes(x = x8, y = x9))
mp + geom_point()

Screenshot of main code listing

mp + geom_point(aes(color = x3, shape = x3), size = 4)

Screenshot of main code listing

Lines

mp + geom_line(size = 2)

Screenshot of main code listing

mp + geom_line(aes(color = x3), size = 2)

Screenshot of main code listing

Smoothed Conditional Means

mp + geom_smooth(method = "loess")

Screenshot of main code listing

mp + geom_smooth(method = "lm")

Screenshot of main code listing

Histogram

xx <- data.frame(data = c(rnorm(50, mean = 40, sd = 10),
                          rnorm(50, mean = 60, sd = 5)),
                 group = factor(rep(1:2, each = 50)),
                 label = c("Label1", rep(NA, 49), "Label2", rep(NA, 49)))
mp <- ggplot(xx, aes(x = data, fill = group))
mp + geom_histogram(color = "black")

Screenshot of main code listing

mp + geom_histogram(color = "black", position = "dodge")

Screenshot of main code listing

mp1 <- mp + geom_histogram(color = "black") + facet_grid(group~.)
mp1

Screenshot of main code listing

Smoothed density estimates

mp + geom_density(alpha = 0.5)

Screenshot of main code listing

Boxplot

mp <- ggplot(xx, aes(x = group, y = data, fill = group))
mp + geom_boxplot(color = "black")

Screenshot of main code listing

mp + geom_boxplot() + geom_point()

Screenshot of main code listing

Violin Plot

mp + geom_violin() + geom_boxplot(width = 0.1, fill = "white")

Screenshot of main code listing

library(ggbeeswarm)
mp + geom_quasirandom()

Additional packages such as ggbeeswarm and ggrepel also contain useful functions to add to the functionality of ggplot2

Screenshot of main code listing

mp + geom_quasirandom(aes(shape = group))

Screenshot of main code listing

mp2 <- mp + geom_violin() + 
  geom_boxplot(width = 0.1, fill = "white") +
  geom_beeswarm(alpha = 0.5)
library(ggrepel)
mp2 + geom_text_repel(aes(label = label), nudge_x = 0.4)

Screenshot of main code listing

library(ggpubr)
ggarrange(mp1, mp2, ncol = 2, widths = c(2,1),
          common.legend = T, legend = "bottom")

Screenshot of main code listing

Key Points

  • Remember to load your ggplot2 library before writing your code

  • Find the best graph meets your need