Search code examples
rggplot2yaxissuperscript

Add superscript to ggbarplot y axis in R


I've tried a few different options but I keep getting an error back. I'm trying to add superscript to the title "Surface Area Consumed (cm^2)", here is the most recent attempt.

ggbarplot(sr, x = "Treatment", y = "SA30",
                  add = "mean_sd", 
                  color = c("chartreuse","chartreuse"), add.params = list(size = 2),
                  fill = "Treatment", palette = c("chartreuse3","chartreuse4"),  
                  ylab = expression("Surface Area Consumed (cm"^2")"), xlab = "", legend = "", legend.title = "") +
  scale_y_continuous(expand = c(0, 0), breaks=seq(0,20,2)) +
  coord_cartesian(ylim=c(0,14)) +
  rremove("ticks") +
  rotate_y_text(45) +
  font("xy.text", color = "seagreen") +
  theme(axis.text.x = element_text(size = 20),
        axis.text.y = element_text(size = 15),
        axis.title.x = element_text(size = 30),
        axis.title.y = element_text(size = 20, color = "seagreen"),
        text=element_text(family="Tw Cen MT Condensed Extra Bold", size=12),
        axis.line = element_line(size = 2, color = "seagreen"))

Example graph with different yaxis title

I'm getting this error back:

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

Any help would be appreciated.


Solution

  • I believe the issue comes from the missing tilde following the 2 in your code. I have provided a reproducible example below of a ylabel using the exact intended text.

    If I understand correctly the ggplot object created could have the labels modified afterwards. I would change the label in an additional labs function to test this.

    library(tidyverse)
    
    mtcars %>% 
      ggplot(aes(x = cyl, y = mpg)) +
       geom_point() +
       labs(y = expression("Surface Area Consumed (cm"^{2}~")"))
    

    Created on 2021-04-05 by the reprex package (v2.0.0)