tags:

views:

163

answers:

1

I'm using ggplot2 to explore the effects of different military operations on murder rates. To show the effect I draw a vertical line when the operation occurred and a smoothed line of the murder rate before and after the operation.

I've written a facet_wrap plot to show this for a whole bunch of counties. It works beautifully, but when converted to a function I get an error when using a local variable to draw the vertical line.

Here's some example code:

drawTS <- function(df, dates, text) {
    p <- ggplot(df, aes(date, murders)) +
      facet_wrap(~ county, ncol = 1,
                 scale="free_y") +
      scale_x_date() +
      geom_smooth(aes(group = group), se = FALSE)
    for(i in 1:length(dates)) {
      #If it's not a global variable I get an object not found error
      temp[i] <<- dates[i]
      p <- p + geom_text(aes(x,y), label = text[i],
                  data = data.frame(x = dates[i], y = -10),
                  size = 3, hjust = 1, vjust = 0) +
           #Here's the problem
           geom_vline(xintercept=temp[i], alpha=.4)
    }
    p
}

library(ggplot2)
df <- data.frame(date = rep(seq(as.Date("2007/1/01"),
                          length=36, by='1 month'),4),
               murders = round(runif(36*4) * 100),
               county = rep(rep(factor(1:4),9),each=4),
               group = rep(c(rep(1,6), rep(2,12),rep(3,18))), each=4)
dates <- c(as.Date("2007/6/15"), as.Date("2008/6/15"))
temp <- c()
drawTS(df, dates, c("Op 1","Op 2"))

There's no error with the global variable, but it looks ugly.

If instead of the temp[i] variable I use dates[i] inside geom_vline(), I get this:

Error in NextMethod("[") : object 'i' not found

If I wrap the variable dates[i] in aes(), I get:

Error in eval(expr, envir, enclos) : object 'county' not found

Anybody know how to fix this?

+1  A: 

I don't know what is causing the error, but a fix that I could come up with is to replace the for loop with a data frame like this:

date.df<-data.frame(d=dates,t=text)
p <- p + geom_text(aes(x=d,label=t),y=0,
                   data = date.df,
                   size = 3, hjust = 1, vjust = 0)
p<-p+geom_vline(aes(xintercept=d),data=date.df,alpha=.4)
Jyotirmoy Bhattacharya
So the trick is to use a second data frame... Thanks!
diegovalle