Topics for today

Themes

Base figure using default ggplot2 theme

p <- ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(cyl))) +
  geom_point()

p

Same figure with builtin cowplot theme

if(!require("cowplot"))   install.packages("cowplot") # plot_grid and so much else

p

Cowplot has other built-in themes that you can explore, including those with minimal gridlines and ones built for mapping. You can explore the code under the themes at https://github.com/wilkelab/cowplot/blob/master/R/themes.R.

Custom theme

Alternatively, you can create a custom theme, which is particularly useful if you’re following the style guides for a journal submission or creating a special set of figures for a poster or presentation. For example, if you want simple theme with a muted panel border and Times New Roman font (HINT: This is Ben’s theme), you can use the following code:

windowsFonts(Times=windowsFont("Times New Roman"))

theme_sleek <- function(base_size = 12, base_family = "Times") {
  half_line <- base_size/2
  theme_light(base_size = 12, base_family = "Times") +
    theme(
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      axis.ticks.length = unit(half_line / 2.2, "pt"),
      strip.background = element_rect(fill = NA, colour = NA),
      strip.text.x = element_text(colour = "black"),
      strip.text.y = element_text(colour = "black"),
      panel.border = element_rect(fill = NA),
      legend.key.size = unit(0.9, "lines"),
      legend.key = element_rect(colour = NA, fill = NA),
      legend.background = element_rect(colour = NA, fill = NA)
    )
}

theme_set(theme_sleek())

p

Once we call a theme using the function theme_set(), it will apply this theme to all subsequent figures. The opportunities for ggplot2 themes are endless, and there are a ton of resources on the web to help you build the themes of your dreams. Another great resource for themes is the ggthemes package, which we will get into a little later.

Custom axis ticks with tickr()

This is a custom function inspired by Ben. It is perfect for defining intervals for tick marks and labels on an axis. I use it most frequently for plotting variables that are integers (e.g. Year or Age class).

Example without tickr()

data("longley")

q <- ggplot(longley, aes(x = Year, y = Employed)) +
  geom_point() +
  geom_line()

q

Example with tickr()

axis <- tickr(longley, Year, 5)

q <- q + scale_x_continuous(breaks = axis$breaks, labels = axis$labels)

q

ADF&G Plotting Library

Ben started an R package that houses theme_sleek() and tickr().

You can access these and any future developments using the following code:

# install.packages("devtools")
# devtools::install_github("ben-williams/FNGr")
# library("FNGr")

Multipanelled plots

There’s been a long history of writing multipanelled plots in R. Remember par(mfrow = c(2,2))? For a long time I used the grid.arrange() function from the gridExtra package, but cowplot’s plot_grid() function makes this process so much easier and fine tuned.

You can check out cowplot’s vignettes on the topic for more advanced topics, but here I’ll show a couple simple examples https://cran.r-project.org/web/packages/cowplot/vignettes/plot_grid.html.

Stacked figure

p <- p + theme(legend.position = "none")

# stack figures (1 column) and align figs horizontally and vertically
pq <- cowplot::plot_grid(p, q, ncol = 1, align = "hv")

pq

Multiple panels of different sizes

r <- ggplot(diamonds, aes(clarity, fill = cut)) + 
  geom_bar() +
  theme(axis.text.x = element_text(angle=45, vjust=0.5))

# Nest multipanelled plots and control the relative sizes of the associated figures
pqr <- cowplot::plot_grid(pq, r, ncol = 2, rel_widths = c(1, 1.3))

pqr

Better labels with ggrepel

The ggrepel package makes labeling your data so much easier using its built-in algorithm for spacing labels. Use it the same way as geom_text().

if(!require("ggrepel"))   install.packages("ggrepel") # geom_text_repel()

# make the row names a separate column
mtcars$car <- row.names(mtcars)

head(mtcars)
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
##                                 car
## Mazda RX4                 Mazda RX4
## Mazda RX4 Wag         Mazda RX4 Wag
## Datsun 710               Datsun 710
## Hornet 4 Drive       Hornet 4 Drive
## Hornet Sportabout Hornet Sportabout
## Valiant                     Valiant
mtcars %>% 
  group_by(cyl) %>% 
  # Subsample data
  sample_frac(0.5, replace = FALSE) -> mtcars2

p <- ggplot(mtcars2, aes(x = wt, y = mpg, colour = factor(cyl), 
                         shape = factor(cyl), label = car)) +
  geom_point() 

a <- p + geom_text(show.legend = FALSE, size = 3) +
  ggtitle("geom_text()")

b <- p + geom_text_repel(show.legend = FALSE, size = 3) +
  ggtitle("geom_text_repel()")

cowplot::plot_grid(a, b, ncol = 1)

Resources for colour

IMHO if you don’t need colour, don’t use it! It’s distracting and if it doesn’t mean anything, what’s the point? Let scale_colour_grey() and scale_fill_grey() help.

r + scale_fill_grey()

But, if you must… here are my favorite colour libraries and resources:

The RColorBrewer library.

Colour blind, print friendly, photocopy safe colour schemes: http://colorbrewer2.org/#type=sequential&scheme=BuGn&n=3

Any colour you could ever want: http://www.color-hex.com

Beautiful colour schemes made by design students: https://www.canva.com/learn/100-color-combinations/

If you decide you want to use any of the Canva colour palettes, you’ll need to download the ggthemes library (and also the RColorBrewer library). The associated names of the palettes from the website above can be found at http://makeadifferencewithdata.com/wp-content/uploads/2016/12/color-palettes.txt.

Here’s an example of how to use a Canva colour palette:

if(!require("RColorBrewer"))   install.packages("RColorBrewer") # colorRampPalette() in this example but also has other uses with ggplot()
if(!require("ggthemes"))   install.packages("ggthemes") # canva_pal() but also has a ton of built-in themes to explore

# Some different options on canva.com
# pal <- ggthemes::canva_pal("Watery blue-greens")(4) 
# pal <- ggthemes::canva_pal("Surf and turf")(4) 
pal <- ggthemes::canva_pal("Warm and cool")(4)
# pal <- ggthemes::canva_pal("Pool party")(4) 
# pal <- ggthemes::canva_pal("Trendy and metropolitan")(4) 
# pal <- ggthemes::canva_pal("Fresh and bright")(4) 

a <- ggplot(sample_frac(diamonds, 0.1, replace = FALSE), 
            aes(x = carat, y = price, colour = cut)) +
  geom_point(alpha = 0.2, size = 1) +
  geom_smooth(se = FALSE, size = 2) + 
  theme(legend.position = "bottom")

# ColorRampPalette increases the number of colour options within your pal
# options to the number of distinct levels of diamond's cut
b <- a + scale_colour_manual(values = colorRampPalette(pal)(n_distinct(diamonds$cut)))

cowplot::plot_grid(a, b, ncol = 1)

The ggthemes library also has a lot of built-in predefined themes. For a list of themes in the package check:

ls("package:ggthemes")[grepl("theme_", ls("package:ggthemes"))]
##  [1] "theme_base"            "theme_calc"           
##  [3] "theme_economist"       "theme_economist_white"
##  [5] "theme_excel"           "theme_excel_new"      
##  [7] "theme_few"             "theme_fivethirtyeight"
##  [9] "theme_foundation"      "theme_gdocs"          
## [11] "theme_hc"              "theme_igray"          
## [13] "theme_map"             "theme_pander"         
## [15] "theme_par"             "theme_solarized"      
## [17] "theme_solarized_2"     "theme_solid"          
## [19] "theme_stata"           "theme_tufte"          
## [21] "theme_wsj"

One last thing

This website is a fun place to learn more about how users have extended the base potential of ggplot2: https://www.ggplot2-exts.org.

Session info

sessionInfo()
## R version 3.5.1 (2018-07-02)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 16299)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=English_United States.1252 
## [2] LC_CTYPE=English_United States.1252   
## [3] LC_MONETARY=English_United States.1252
## [4] LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.1252    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] ggthemes_4.0.0     RColorBrewer_1.1-2 ggrepel_0.8.0     
##  [4] bindrcpp_0.2.2     cowplot_0.9.2      knitr_1.20        
##  [7] forcats_0.3.0      stringr_1.3.1      dplyr_0.7.6       
## [10] purrr_0.2.5        readr_1.1.1        tidyr_0.8.1       
## [13] tibble_1.4.2       ggplot2_3.0.0      tidyverse_1.2.1   
## 
## loaded via a namespace (and not attached):
##  [1] tidyselect_0.2.4  reshape2_1.4.3    haven_1.1.2      
##  [4] lattice_0.20-35   colorspace_1.3-2  viridisLite_0.3.0
##  [7] htmltools_0.3.6   mgcv_1.8-24       yaml_2.1.19      
## [10] rlang_0.2.1       pillar_1.2.3      foreign_0.8-70   
## [13] glue_1.2.0        withr_2.1.2       modelr_0.1.2     
## [16] readxl_1.1.0      bindr_0.1.1       plyr_1.8.4       
## [19] munsell_0.5.0     gtable_0.2.0      cellranger_1.1.0 
## [22] rvest_0.3.2       psych_1.8.4       evaluate_0.10.1  
## [25] labeling_0.3      parallel_3.5.1    broom_0.4.5      
## [28] Rcpp_0.12.17      scales_0.5.0      backports_1.1.2  
## [31] jsonlite_1.5      mnormt_1.5-5      hms_0.4.2        
## [34] digest_0.6.15     stringi_1.1.7     grid_3.5.1       
## [37] rprojroot_1.3-2   cli_1.0.0         tools_3.5.1      
## [40] magrittr_1.5      lazyeval_0.2.1    crayon_1.3.4     
## [43] pkgconfig_2.0.1   Matrix_1.2-14     xml2_1.2.0       
## [46] lubridate_1.7.4   assertthat_0.2.0  rmarkdown_1.10   
## [49] httr_1.3.1        rstudioapi_0.7    R6_2.2.2         
## [52] nlme_3.1-137      compiler_3.5.1