Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using bquote() and expression(paste()) for labels in ggplot2

Tags:

r

ggplot2

So both lines of ggplot gets about the same graph, but which one is preferred? I normally see either one or another, but I couldn't find an explicit comparison between the two. Any light shined on this would be appreciated, thanks!

library(ggplot2)
ggplot(cars, aes(x=dist, y=speed))+geom_line()+labs(x='Distance travelled in m', y=expression(paste('Speed in' * m^2)))

enter image description here

ggplot(cars, aes(x=dist, y=speed))+geom_line()+labs(x='Distance travelled in m', y=bquote('Speed in' * m^2))

Using bquote

edit: I realised I forgot a space after 'in' in ylab, ignore that mistake...

like image 634
Arashi Avatar asked Oct 31 '22 06:10

Arashi


1 Answers

expression('Speed in' ~ m^2)

~ produces a space and different arguments to paste are separated by , (but paste is not needed here). See help("plotmath").

bquote is a different beast. It let's you do this:

unit <- quote(m^2)
ggplot(cars, aes(x=dist, y=speed))+
  geom_line()+
  labs(x='Distance travelled in m', 
       y=bquote('Speed in' ~ .(unit)))
like image 177
Roland Avatar answered Nov 15 '22 05:11

Roland