How to get geom_vline and facet_wrap from ggplot2 to work inside a function

I use ggplot2 to study the effects of various military operations on killings. To show the effect, I draw a vertical line when the operation took place, and a smooth line of the kill level before and after the operation.

I wrote a facet_wrap chart to show this for a whole group of counties. It works beautifully, but when converting to a function, I get an error when using a local variable to draw a vertical line.

Here is a sample 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 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 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 is no error in a global variable, but it looks ugly.

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

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

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

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

Does anyone know how to fix this?

+4
source share
1 answer

I don't know what causes the error, but the fix 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) 
+3
source

Source: https://habr.com/ru/post/1301397/


All Articles