Search code examples
rggplot2geom-text

How to make R and p italic in geom_text()


Update with the facet part the plot should look like this unless R and p (the letters) should be italic:

mtcars %>% 
  ggplot(aes(x=mpg, y=disp, color = factor(am)))+
  geom_point()+
  geom_text(aes(x = 25, y = 500,
                label = ifelse(am == 0, "R = 0.5998324, p = 0.0002", "")),
            color = "black")+
  facet_wrap(. ~ am)

enter image description here

Original question I have this example plot:

library(dplyr)
library(ggplot)

mtcars %>% 
  ggplot(aes(x=mpg, y=disp, color = factor(am)))+
  geom_point()+
  geom_text(aes(x = 25, y = 300,
                label = ifelse(am == 0, expression(paste("R = 0.5998324, ", italic("p = 0.0002"))), "")),
            color = "black")

enter image description here I would like to make R and p in geom_text() italic:

I tried with expression:

mtcars %>% 
  ggplot(aes(x=mpg, y=disp, color = factor(am)))+
  geom_point()+
  geom_text(aes(x = 25, y = 300,
                label = ifelse(am == 0, expression(paste("R = 0.5998324, ", italic("p = 0.0002"))), "")),
            color = "black")

I get this error:

Don't know how to automatically pick scale
for object of type <expression>. Defaulting
to continuous.
Error in `geom_text()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 2nd layer.
Caused by error in `compute_aesthetics()`:
! Aesthetics are not valid data
  columns.
✖ The following aesthetics are invalid:
✖ `label = ifelse(...)`
ℹ Did you mistype the name of a data column
  or forget to add `after_stat()`?

How could I fix? The ifelse is important because in real life I facet the data and using unicode makes it possible but changes the font!


Solution

  • Another option using parse=TRUE in geom_text with italic while keeping the ifelse like this:

    library(tidyverse)
    mtcars %>% 
      ggplot(aes(x=mpg, y=disp, color = factor(am)))+
      geom_point()+
      geom_text(aes(x = 25, y = 500,
                    label = ifelse(am == 0, 'paste(italic("R")," = 0.5998324, ",italic("p")," = 0.0002")', "")),
                color = "black",
                parse = TRUE)+
      facet_wrap(. ~ am)
    

    Created on 2023-05-04 with reprex v2.0.2