Search code examples
rggplot2axis-labelssuperscript

How do I add a superscripted comma and a space in a ggplot2 axis tick label?


I am trying to add superscripts to my y axis tick labels in ggplot2. I want the labels to look like this:

ATRS20m,0f (where the 0f and 0m are superscripted). This produces an error that looks like this.

Error in parse(text = levels(diff_30$Station)) :
<text>:1:8: unexpected symbol
1: ATRS2^0m0f ^

I realize that what I am parsing is not an R expression of any sort, which is why it is failing. But how do I get this to work? There must be some way.

My code to create the label looks like this:

paste(missing_df$Station,paste('^',missing_df$Precip_30_m,"m,",missing_df$TMin_30_f,"f",sep=''),sep='')

My ggplot code to plot and produce the labels looks like this.

plot + scale_y_discrete(labels = parse(text = levels(diff_30$Station)))

I've tried using this, but that fails. I've looked at bquote, which might work, but that syntax is confusing me even more.

plot + scale_y_discrete(labels = expression(parse(text = levels(diff_30$Station))))

Any help would be wonderful. Thank you!


Solution

  • Let's see if the next piece of code does the trick you are looking for:

    data("iris")
    
    #vector from factor levels 
    strtest <- levels(iris$Species)
    
    #We build the "label" and leave the result as a list
    labels <- lapply(strtest, function(x) bquote(.(x)^'0m,0f'))
    
    #Plotting
    ggplot(iris,aes(x = Sepal.Length, y = Species))+
      geom_point() +
      #we use do.call to "apply" function 'expression' to each element of the list label
      scale_y_discrete(labels=do.call(expression,labels))
    

    Result:

    enter image description here