Search code examples
rggplot2

How to add a subscript with other characters in the title using ggplot in R?


I want the graph's title to show "the title is m0", in which 0 is placed as a subscript next to "m". I am using the expression() but it works without other characters, while fail to make it a subscript when other characters are present. How can we fix this?

data("iris")

ggplot(data=iris,mapping=aes(x=Petal.Length,y=Petal.Width,color=Species))+
    geom_point()+
    geom_smooth(method="lm") +
    labs(title = paste0("the title is ", expression(m[0])))

The resulting graph looks like enter image description here

See that the title does not give what I want by displaying [0] rather than 0 (subscript).


Solution

  • Use paste rather than paste0 and change the calls to expression and paste like so.

    data("iris")
    library(ggplot2)
    ggplot(data=iris,mapping=aes(x=Petal.Length,y=Petal.Width,color=Species))+
      geom_point()+
      geom_smooth(method="lm") +
      labs(title = expression(paste('The title is ', m[0])))
    

    with subscript

    I'm not sure why paste0 doesn't work.