Diagram types with the ggplot2 package

Install required packages

ggplot2, ggbeeswarm, cowplot, patchwork

Simulate data

Diagram types

Scatterplot

plot of chunk ggplot_types01
plot of chunk ggplot_types01

Line plot

group=TRUE is necessary here

    group   mood
1 control  82.33
2 placebo  96.75
3  treatA 114.93
4  treatB 107.89
plot of chunk ggplot_types02a
plot of chunk ggplot_types02a
    group   mood
1 control  82.33
2 placebo  96.75
3  treatA 114.93
4  treatB 107.89
plot of chunk ggplot_types02b
plot of chunk ggplot_types02b

Barplot

Absolute frequencies

plot of chunk ggplot_types03
plot of chunk ggplot_types03

Relative frequencies

plot of chunk ggplot_types04
plot of chunk ggplot_types04

Histogram

Absolute frequencies

plot of chunk ggplot_types06
plot of chunk ggplot_types06

Density with nonparametric kernel density estimator

plot of chunk ggplot_types07
plot of chunk ggplot_types07

Boxplot

Add a geom_beeswarm() layer to show raw data.

plot of chunk ggplot_types08
plot of chunk ggplot_types08

Q-Q plot

Against normal distribution

plot of chunk ggplot_types09
plot of chunk ggplot_types09

Against pre-specified distribution (here: t)

plot of chunk ggplot_types10
plot of chunk ggplot_types10

Compare quantiles of two variables

plot of chunk ggplot_types11
plot of chunk ggplot_types11

Multi-panel plots

Split the diagram into panels by column using facet_grid().

plot of chunk ggplot_types12a
plot of chunk ggplot_types12a

Split the diagram into matrix of panels using facet_wrap(). Option scales="free_y" produces separate y-axis for each panel.

plot of chunk ggplot_types12b
plot of chunk ggplot_types12b

Additional diagram elements

Add error bars

Error in fix.by(by.x, x): 'by' must specify a uniquely valid column
Error in merge(groupMSD, groupN, by = c("sex", "group")): object 'groupMSD' not found
Error in transform(groupMSDN, SEMlo = mood.M - mood.SD/sqrt(Freq), SEMup = mood.M + : object 'groupMSDN' not found
Error in ggplot(groupMSDN, aes(x = group, y = mood.M, ymin = SEMlo, ymax = SEMup, : object 'groupMSDN' not found
  • geom_hline() for a horizontal line
  • geom_vline() for a vertical line
  • geom_smooth() for a regression line including SEs
  • geom_text() for text from a variable
  • ggtitle() for a diagram title
  • annotate() for text given directly as an argument
plot of chunk ggplot_types14
plot of chunk ggplot_types14

Put different plots on the same page

Using package cowplot

plot of chunk ggplot_types15
plot of chunk ggplot_types15

Using package patchwork

plot of chunk ggplot_types16
plot of chunk ggplot_types16
plot of chunk ggplot_types17
plot of chunk ggplot_types17

Save ggplot2 diagrams to file

Graphics file format is determined from file ending.

Further online resources

See Cookbook for R: ggplot2 diagrams for many detailed examples of ggplot2 diagrams.

Detach (automatically) loaded packages (if possible)

Get the article source from GitHub

R markdown - markdown - R code - all posts