Search code examples
rfunctionggplot2axis-labels

R ggplot2: How to get a function in with the text of the axis title?


I would like my plot axis title to include among the text a function that performs a calculation on some data.

For example here are some data

a<-data.frame(time="1000",x=rnorm(10,12,3))
b<-data.frame(time="2000",x=rnorm(50,13,4))
c<-data.frame(time="3500",x=rnorm(50,12,4))
d<-data.frame(time="5000",x=rnorm(7,14,5))
e<-data.frame(time="7000",x=rnorm(20,10,3))
f<-data.frame(time="7500",x=rnorm(15,11,3))
g<-data.frame(time="9000",x=rnorm(15,10,5))
h<-data.frame(time="9500",x=rnorm(35,30,2))
i<-data.frame(time="10000",x=rnorm(30,28,4))
a2i<-rbind(a,b,c,d,e,f,g,h,i) 

library(ggplot2)
a2i$time<-as.numeric(levels(a2i$time))[a2i$time] 
ggplot(a2i,aes(time,x))+stat_smooth()+geom_point()+
# now let's try to put on a label with a function
# mixed in with the text
#
xlab("Time (total number of observations = paste(length(a2i$x))))")
#
# but that's no good, the function is not executed, just printed
# How can I get a function to work in the axis title?

enter image description here

I'd like to keep "time" in the title as a constant, but have the function return different results as the data change. And get the parentheses in there as well.

I've had a go with paste() and expression(), but I'm not having much luck. Any tips would be greatly appreciated.


Solution

  • You should first build a string that contains the test you want, with paste or sprintf, and then feed it to xlab. In particular, paste should not be inside the string.

    xlab( paste( 
      "Time (total number of observations = ", 
      length(a2i$x), 
      ")", 
      sep="" 
    ) )
    
    # Equivalently
    xlab( sprintf( 
      "Time (total number of observations = %s)", 
      length(a2i$x) 
    ) )