Search code examples
rggplot2subscriptgeom-text

How to type subscripts in geom_text labels in ggplot


I have timeseries data plotted and separated by timepoints that I'd like to label with subscripts. Below is the code I'm using to generate the figure and timepoint labels. I'd like for the -1, 3 and 6 to be subscripts. Thanks in advance!

timepoints=data.frame(date=as_datetime(c("2016-08-15" ,"2016-11-22", 
"2017-02-25")), timepoint=c("T-1", "T3", "T6"))

TimeseriespH = ggplot(FinalSeaphox, aes(x=DTTM)) +
geom_line(aes(y=MpH, color = "Outer Bay", group = grp), size = 0.5) +
geom_line(aes(y=CpH, color = "Inner Bay", group = grp), size = 0.5) +
scale_x_datetime(labels = date_format("%b '%y"), date_breaks = "1 
month", limits = as_datetime(c("2016-07-01","2017-04-19"))) +
labs(x = "", y = "pH") +
scale_y_continuous(limits = c(7.4,8.2)) +
geom_vline(xintercept = as_datetime("2016-12-01"), linetype = 2, color 
= "black") +
geom_vline(xintercept = as_datetime("2016-08-26"), linetype = 2, color 
= "black") +
geom_vline(xintercept = as_datetime("2017-03-06"), linetype = 2, color 
= "black") +
geom_text(data=timepoints, mapping=aes(x=date, y=c(8.18, 8.18, 8.18), 
label=timepoint), size=5, vjust=-0.4, hjust=0, inherit.aes = FALSE, 
color = "black")  

Solution

  • For the subscripts, you need to enclose between brackets:

    timepoint = c("T[-1]", "T[3]", "T[6]")
    

    Then use parse = TRUE in geom_text:

    library(ggplot2)
    library(lubridate)
    
    timepoints=data.frame(
      date = as_datetime(c("2016-08-15" ,"2016-11-22", "2017-02-25")), 
      Y = c(8, 8.1, 8)
      timepoint = c("T[-1]", "T[3]", "T[6]")
    )
    ggplot(timepoints) +
      geom_point(aes(x = date, y=Y), size = 3) +
      geom_text(data=timepoints, 
                mapping=aes(x=date, y=c(8.18, 8.18, 8.18), 
                            label = timepoint), 
                size=5, vjust=0.4, hjust=0, inherit.aes = FALSE, 
                color = "black", parse = TRUE) 
    

    enter image description here