Home > Back-end >  Why paste0() is not working properly inside expression() in either ggplot2 or baseplot
Why paste0() is not working properly inside expression() in either ggplot2 or baseplot

Time:07-20

If I want to use paste0 inside expression to label the x-axis, it's not working as intended. But paste works.

library(ggplot2)

ggplot(mtcars, aes(mpg, disp))  
  geom_point()  
  labs(
    x = expression(paste0("It's","mpg")^("paste0 is not working")),
    y = expression(paste("It's ", "disp")^("paste is working")), # had to give extra space
  )

ggplot with wrong behavior of paste0

Please Note that

  • I have used paste0 in x-axis, which is not showing as intended
  • used paste in **y-axis which is working, but had to give extra space to separate It's and disp, which should be the default behavior of paste (AFAIK). But that default behavior is not working inside the expression.

Also same happens with base-plot

plot(mtcars$disp ~ mtcars$mpg, 
     xlab = expression(paste0("mpg")^("paste0 is not working")),
     ylab = expression(paste("disp")^("paste is working"))
     )

base plot with wrong behavior of paste0

Can anyone please break this out for me,

  • why paste0 is not working?
  • and also why pastes default behavior is not preserved here??

What's going on here? Thanks.

CodePudding user response:

It seems you can only use the operations listed in ?plotmath.

https://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/plotmath.html

paste is there, but paste0 is not. Also, the function features are not equivalent to the R's functions of the same name.

  • Related