ggplot tips: markdown for italics in plots and adding breaks to color scaling

code
beginner
r
tips
ggplot
Author

Daniel Kick

Published

March 5, 2021

Two tricks today: 1. Scale fill functions can accept breaks and limit arguments so you don’t have to use hacky workarounds like binning the data before plotting (which is what I usually do). 2. library(ggtext) lets you render markdown within plots (e.g. for those pesky mRNAs)

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.0     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
set.seed(42)
df <- do.call(cbind, map(
  1:5, 
  function(e){
    data.frame(gene = rnorm(10))
    })
  )

df <- df |>
  corrr::correlate() |>
  corrr::shave() |> 
  pivot_longer(cols = starts_with('gene')) |> 
  rename(term2 = name, Cor = value) |> 
  drop_na()
Correlation computed with
• Method: 'pearson'
• Missing treated using: 'pairwise.complete.obs'
head(df)
# A tibble: 6 × 3
  term   term2      Cor
  <chr>  <chr>    <dbl>
1 gene.1 gene   -0.375 
2 gene.2 gene    0.440 
3 gene.2 gene.1 -0.153 
4 gene.3 gene   -0.404 
5 gene.3 gene.1  0.465 
6 gene.3 gene.2 -0.0600

Before:

df |> 
  ggplot(aes(term, term2, fill = Cor))+ 
  geom_tile()+ labs(x = "mRNA", y = "")+ 
  scale_fill_distiller(palette = "PuOr")+ 
  coord_fixed()

After:

library(ggtext) # https://github.com/wilkelab/ggtext
library(glue)

df |> 
  mutate(term = glue(("<i>{term}</i>"))) |>
  ggplot(aes(term, term2, fill = Cor))+ 
  geom_tile()+ labs(x = "mRNA", y = "")+ 
  theme(axis.text.x = element_markdown(angle = 45))+ # <-- Note that we have element_markdown not element_text
scale_fill_stepsn(
  colors=RColorBrewer::brewer.pal(n = 8, name = "PuOr"), 
  na.value = "transparent", breaks=round(seq(-1, 1, length.out =8), digits = 2), 
  limits=c(-1,1) )