I have a df with several y-series that I want to display individually, so I wrote fn that selects one specific series, assigning a local variable to dat , and then displays it. However, ggplot / geom_step when called inside fn does not handle it properly, as a separate series. I donβt see how this can be a problem, since if dat not visible, then ggplot probably failed?
You can verify the correctness of the code when executed from the toplevel environment, but not inside the function. This is not a duplicate question. I understand the problem (this is a recurring problem with ggplot), but I read all the other answers; this is not a duplicate, and they do not provide a solution. 
set.seed(1234) require(ggplot2) require(scales) N = 10 df <- data.frame(x = 1:N, id_ = c(rep(20,N), rep(25,N), rep(33,N)), y = c(runif(N, 1.2e6, 2.9e6), runif(N, 5.8e5, 8.9e5) ,runif(N, 2.4e5, 3.3e5)), row.names=NULL) plot_series <- function(id_, envir=environment()) { dat <- subset(df,id_==id_) p <- ggplot(data=dat, mapping=aes(x,y), color='red') + geom_step()