ggplot practice:

Load libraries

library(ggplot2)
library(ggthemes)
library(patchwork)

Set up data and initial ggplot graph

data <- PlantGrowth
print(data)
##    weight group
## 1    4.17  ctrl
## 2    5.58  ctrl
## 3    5.18  ctrl
## 4    6.11  ctrl
## 5    4.50  ctrl
## 6    4.61  ctrl
## 7    5.17  ctrl
## 8    4.53  ctrl
## 9    5.33  ctrl
## 10   5.14  ctrl
## 11   4.81  trt1
## 12   4.17  trt1
## 13   4.41  trt1
## 14   3.59  trt1
## 15   5.87  trt1
## 16   3.83  trt1
## 17   6.03  trt1
## 18   4.89  trt1
## 19   4.32  trt1
## 20   4.69  trt1
## 21   6.31  trt2
## 22   5.12  trt2
## 23   5.54  trt2
## 24   5.50  trt2
## 25   5.37  trt2
## 26   5.29  trt2
## 27   4.92  trt2
## 28   6.15  trt2
## 29   5.80  trt2
## 30   5.26  trt2
p1 <- ggplot(data=data, aes(x=group,y=weight)) + geom_boxplot()
print(p1)

Themes

p1 + theme_bw() # grid lines, not too dark

p1 + theme_classic() # no grid lines and white background

p1 + theme_linedraw() # black frame

p1 + theme_dark() # good for brightly colored points

p1 + theme_base() # mimics graphs created using base R, good for working with others who are using base R

p1 + theme_par() # again, matches current par settings in base

p1 + theme_void() # shows data only, good for overlaying on a figure or something

p1 + theme_solarized() # good for web pages

p1 + theme_economist() # many specialized themes

p1 + theme_grey() # ggplot default theme if you're trying to get back to original

Base sizes

p1 + theme_classic(base_size=10)

p1 + theme_classic(base_size=20)

p1 + theme_classic(base_size=30)

p1 + theme_classic(base_size=40)

Aesthetics/mapping

p1 <- ggplot(data=data, aes(x=group,y=weight)) + aes(fill=I("goldenrod"),col=I("black")) + geom_boxplot()
p1

p2 <- ggplot(data=data, aes(x=group,y=weight)) + aes(fill=I("coral"),col=I("black")) + geom_boxplot()
p2

p3 <- ggplot(data=data, aes(x=group,y=weight)) + aes(fill=I("blue"),col=I("black")) + geom_boxplot()
p3

p1 <- ggplot(data=data, aes(x=group,y=weight))
p1 + geom_boxplot(aes(fill = factor(group)))

Faceting

p1 + facet_grid(cols=vars(group)) + geom_boxplot()

Exporting to pdf

ggsave(plot=p1, filename="MyPlot",width=5,height=3,units="in",device="pdf")

Going farther: labels, annotations, lines/arrows, custom colors

p1 <- ggplot(data=data, aes(x=group,y=weight)) +
  theme_linedraw() +
  geom_boxplot(aes(fill = factor(group))) + 
  theme(legend.position="none") +
  labs(title="Effect of Treatment on Plant Height", x = "Group", y="Weight", caption="Data source: R")
p1