Search code examples
rggplot2tidyversefacet-gridgeom-text

How to combine italic and non-italic components of a `geom_text` call. Add `geom_text` labels to a series of `facet_grid` scatter plots


I'd like to include a text label that indicates the correlation coefficient on a series of facet_wrapped scatterplots (eg: "r = -0.52").

So my scatterplots look something like this:

library(tidyverse)
df <- mtcars
df %>% 
  ggplot(aes(y = mpg, x = hp)) +
  geom_point(colour = "blue") + 
  facet_grid(~ factor(cyl))

Created on 2019-06-26 by the reprex package (v0.2.1)

I've then tried to create three separate correlation coefficients, after grouping, and I'd like the label to show up on the diagram, but it's not quite right. I'd like it to say something like: "r = -0.52"

library(tidyverse)
df <- mtcars
df2 <- df %>% 
  group_by(cyl) %>% 
  summarise(correlation = cor(y = mpg, x = hp, use = "pairwise.complete.obs"))
df2
#> # A tibble: 3 x 2
#>     cyl correlation
#>   <dbl>       <dbl>
#> 1     4      -0.524
#> 2     6      -0.127
#> 3     8      -0.284
df <- left_join(df, df2, by = "cyl")

df %>% 
  ggplot(aes(y = mpg, x = hp)) +
  geom_point(colour = "blue") +
  geom_text(x = 200, y = 30, label = expression(paste(italic(r), " = ", df$correlation))) +
  facet_grid(~ factor(cyl))
#> Warning in is.na(x): is.na() applied to non-(list or vector) of type
#> 'expression'

Created on 2019-06-26 by the reprex package (v0.2.1)


Solution

  • You can do

      geom_text(x = 200, y = 30, 
                label = paste0("italic(r) == ", df$correlation), parse = TRUE) 
    

    To display a rounded correlation:

      geom_text(x = 200, y = 30, 
                label = paste0("italic(r) == ", round(df$correlation,2)), parse = TRUE)