1

I am trying to produce a list of ggplot2 graphs with different timedate format labels on the x axe. Yet the format argument is not taken into account as expected by ggplot. Here is the minimal code that can reproduce the issue.

x<-as.POSIXct(strptime(c("2013-01-01 00:00:00","2013-01-02 00:00:00"),format="%Y-%m-%d %H:%M:%S"))
y1<-c(0,1)
y2<-c(0,-1)
df<-data.frame(x=x,y1=y1,y2=y2)
f<-function(a,b){ggplot(df,aes_string(x="x",y=b))+geom_line()+ scale_x_datetime(labels= date_format(a))}
r<-mapply(f,c("%b-%d","%H:%M"),c("y1","y2"),SIMPLIFY=FALSE)

r[2] gives the expected plot (sorry I can not post pictures) but for r[1] the axes format is not correct (whereas the data to plot is correctly taken into account).

any suggestions?

user2147028
  • 1,281
  • 13
  • 19

1 Answers1

1

Between ggplot environments and mapply and promise evaluation, a is not being evaluated appropriately, you can get around this by forceing it within the function

eg

f<-function(a,b){
  a <- force(a)
  ggplot(df,aes_string(x="x",y=b))+geom_line()+ scale_x_datetime(labels= date_format(a))
}
r <- mapply(f,c("%b-%d","%H:%M"),c("y1","y2"), SIMPLIFY = FALSE)

r[1]

enter image description here

r[2]

enter image description here

Explain a lazy evaluation quirk explains the lazy evalation in more detail.

Community
  • 1
  • 1
mnel
  • 113,303
  • 27
  • 265
  • 254