Search code examples
rggplot2subscript

Subscripting letters in complex ggplot2 title


I want to subscript letters in a title that includes the word "in" in the title and it's proving to be quite the headache. I've looked at this thread and tried to translate it for my purposes but have not had any success.

I want to create a title that says "Growth Rate in SMMAsn" where the "Asn" is subscripted. If I do the standard quoted title it obviously shows up as is.

When I try to use

labs(title=expression(Growth Rate 'in' SMM[Asn]))

I get an error:

Error: Cannot add ggproto objects together. Did you forget to add this object to a ggplot object?

There is also an error indicated by R Studio at that line that says:

unexpected token: 'Rate'
unexpected token: 'SMM'
unexpected token: '['
unexpected closing bracket: ']'
unmatched opening bracket: '('
unexpected token: ')'

Just to see if I could get the subscripting to work at all, I tried using the expression function for just the word that needed to be subscripted:

labs(title = expression(SMM[Asn]))

That worked just fine! I got real excited and thought, since everything after the "Growth" part of the expression gives me some kind of error, I can maybe concatenate the rest of the title and the part that needs subscripting with the expression function:

labs(title=c("Growth Rate in", (expression(SMM[Asn]))))

All that does is give me a title that says "Growth Rate in" leaving the part that needed to be subscripted out of the title entirely.

I'm kind of at a loss here. I have no formal training in any language aside from R so I'm concerned it's some basic coding logic thing that I'm missing, but it's exhausting me and I can't figure it out. Any advice on how to ameliorate this situation would be greatly appreciated.

If it helps here is the entire context:

ggplot(klett.smm.asn2, aes(x=Strain, y=Generations.hr, fill=Strain))+
  geom_bar(stat="identity", width = 0.7, color="black")+
  geom_errorbar(aes(ymin=Generations.hr-StDev, ymax=Generations.hr+StDev), width=.1, size = 1)+
  theme(axis.text.x=element_text(hjust=.5, vjust=1))+
  theme(text=element_text(size=30), 
        plot.title = element_text(hjust = 0.5),
        legend.position="none",
        axis.title.x = element_blank() )+
  ylab("Generations/hr")+
  #labs(title=expression(Growth Rate 'in' SMM[Asn]))+
  #labs(title = expression(SMM[Asn]))
  labs(title=c("Growth Rate in", (expression(SMM[Asn]))))+
  scale_fill_manual(values=c("#A0A0A0","#45b500", "#00b3f2", "#ff61c7"))+
  scale_y_continuous(limits=c(0,0.9))+
  geom_text(x = 4, y = 0.9, label = "**", size = 10)+
  geom_text(x = 3, y = 0.88, label = "**", size = 10)+
  geom_text(x = 2, y = 0.84, label = "*", size = 10)

Solution

  • The title can be a formula with words separated by tildes. Using the built-in BOD:

    library(ggplot2)
    ggplot(BOD, aes(Time, demand)) +
      geom_line() +
      labs(title = Growth ~ Rate ~ 'in' ~ SMM[Asn])
    

    screenshot