Format ggplot2 diagrams

Install required packages

ggplot2, colorspace

Simulate data

Data needs to be in long format.

Control element position

Side-by-side = “dodge”

plot of chunk ggplot_format01a
plot of chunk ggplot_format01a

Random jitter - useful for overlapping points, e.g., when variables are integer.

plot of chunk ggplot_format01b
plot of chunk ggplot_format01b
plot of chunk ggplot_format01c
plot of chunk ggplot_format01c
plot of chunk ggplot_format01d
plot of chunk ggplot_format01d

Format axes

Change order of categories by changing order of factor levels.

[1] "A" "B" "C"
plot of chunk ggplot_format02
plot of chunk ggplot_format02

Rotate x-axis labels and fine tune x-axis limits / breaks.

plot of chunk ggplot_format03
plot of chunk ggplot_format03

Flip x- and y-axis

plot of chunk ggplot_format04
plot of chunk ggplot_format04

Format legend

plot of chunk ggplot_format05
plot of chunk ggplot_format05

Format color, shape and line type

  sex     group   mood
1   f   control  89.52
2   m   control  86.16
3   f   placebo 104.60
4   m   placebo  91.68
5   f treatment 122.98
6   m treatment 101.42
plot of chunk ggplot_format06
plot of chunk ggplot_format06
plot of chunk ggplot_format06
plot of chunk ggplot_format06

Use themes for a collection of pre-set formatting choices.

plot of chunk ggplot_format07
plot of chunk ggplot_format07
plot of chunk ggplot_format08
plot of chunk ggplot_format08

Further 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