如何在ggplot2中使用geom_vline和facet_wrap函数?

4
我正在使用ggplot2探索不同军事行动对谋杀率的影响。为了展示效果,我在行动发生时绘制一条垂直线,并绘制操作前后的谋杀率平滑曲线。
我编写了一个facet_wrap图来展示所有县的情况。它工作得很好,但是当转换为函数时,如果使用局部变量绘制垂直线,则会出现错误。
以下是一些示例代码:
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"))

全局变量没有错误,但是看起来很丑陋。

如果我在geom_vline()中使用dates[i]而不是temp[i]变量,则会出现以下错误:

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

如果我把变量dates[i]包装在aes()中,则会出现以下错误:

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

有人知道如何解决这个问题吗?

1个回答

3

我不知道是什么原因导致了错误,但是我能想到的解决方法是用数据框替换for循环,就像这样:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接