0

What I have is some data I want to plot with long y axis labels I am adding via facet labels:

library(ggplot2)
data("mtcars")
mtcars$am<-factor(mtcars$am,levels = c("1","0"),
    labels = c("paste('Amerikee C  (mg C kg  ', tuna^-1,')')",#, mg[3]^-phantom(.)-N,', kg ha')^-1",
                                   "paste('Is watchin  ',\n,'(mg  ', CO[2], ' kg tuna'^-1,d^-1,')')"))

What I want is both wrapping / new lines (like \n or str_wrap or strwrap) AND the plotmath for the superscripts and subscripts in the labels.

Like this MS Paint masterpiece. enter image description here

What I've tried is label_wrap_gen() and label_parsed. How do I combine the wrapping of the former with the plotmath parsing of the latter, on a plot with multiple facets?

#This wraps the labels but doesnt parse the plotmath
ggplot(data=mtcars,aes(x=mpg,y=disp))+
    geom_point()+
 facet_wrap(am~.,scales=("free_y"),
             strip.position = "left",
             labeller = label_wrap_gen()) #
    labeller=label_parsed)+ylab("")
 
#This parses the plotmath but doesnt wrap the labels
ggplot(data=mtcars,aes(x=mpg,y=disp))+
    geom_point()+
 facet_wrap(am~.,scales=("free_y"),
             strip.position = "left",
             labeller = label_parsed)+ylab("")

#Note also it ignores the \n's i put in the factor labels

This answer would have gotten me close but it doesn't work anymore.

CrunchyTopping
  • 803
  • 7
  • 17

1 Answers1

1

I think the plotmath bit you might be looking for is the atop() function.

library(ggplot2)
data("mtcars")
mtcars$am<-factor(
  mtcars$am,levels = c("1","0"),
  labels = c("atop('Amerikee C','(mg C kg  tuna^-1)')",
             "atop('Is watchin','(mg  CO'[2]*' kg tuna'^-1*'d'^-1*')')"))


ggplot(data=mtcars,aes(x=mpg,y=disp))+
  geom_point()+
  facet_wrap(am~.,scales=("free_y"),
             strip.position = "left",
             labeller = label_parsed)

Created on 2021-02-11 by the reprex package (v1.0.0)

teunbrand
  • 33,645
  • 4
  • 37
  • 63