Switching between discrete and continuous representations

library(tidyverse)
data("diamonds")

ggplot(diamonds) + 
  geom_point(aes(carat, price))

# hard to see anything going on
ggplot(diamonds) + 
  geom_point(aes(carat, price, colour = depth))

# cut depth into five equisized groups, instead
ggplot(diamonds) + 
  geom_point(aes(carat, price, colour = cut_number(depth, 5)))

# clarity is treated as a discrete variable because it's a factor
ggplot(diamonds) + 
  geom_point(aes(carat, price, colour = clarity))

# this works, but in general I wouldn't recommend turning categories
# into numbers.
ggplot(diamonds) + 
  geom_point(aes(carat, price, colour = as.numeric(clarity)))

# You can also use these techniques to add summaries to a plot
ggplot(diamonds, aes(carat, price)) + 
  geom_point(size = 0.5) +
  geom_boxplot(aes(group = cut_interval(carat, 20)))

Themes

Using built in themes:

ggplot(diamonds) + 
  geom_point(aes(carat, price)) +
  theme_bw()

Specifying individual elements:

ggplot(diamonds) + 
  geom_point(aes(carat, price)) +
  theme(axis.title.x = element_text(family = "mono"))

Using the ggthemes packages:

#install.packages("ggthemes)
library(ggthemes) # you probably need to install it first 
ggplot(diamonds, aes(cut)) +
  geom_bar(aes(fill = clarity)) + 
  scale_fill_excel() + 
  theme_excel()
## Warning: This manual palette can handle a maximum of 7 values. You have supplied
## 8.

Saving Plots

Save plot objects to be called later:

p <- ggplot(diamonds) + 
  geom_point(aes(carat, price))
p 

p + theme_bw()

p + facet_wrap(~ color)

Save you plot as a .pdf or .png

ggsave("my_plot.pdf", height = 6, width = 8) # saves the last plot
ggsave("my_plot.png", height = 6, width = 8)
ggsave("my_plot.pdf", p, height = 6, width = 8) # saves plot is object called p

Note: Modified from notes from Charlotte Wickham