0

As is any method to use geom_ribbon in cycle. I try, but meet a problem. This is my try:

library(ggplot2)
# Create data
huron <- data.frame(year = 1875:1972, level = as.vector(LakeHuron))

m <- 1500 #weight of shadow-line

#Base graph
h <- ggplot(huron, aes(year))+geom_line(aes(x=year, y=level), color='blue')+theme_bw()
count <- 5 # count shadow-lines
start_alpha <- 0.1  # Initial aplha

p <-h
for (i in 0:count-1)
{
  p <- p + 
    geom_ribbon(aes(ymin=level-(level/m)*i,  ymax=level-(level/m)*(i+1)), alpha=start_alpha-(start_alpha/count)*i, fill='blue')
}
print(p)

I investigate the result. It seems that i-cycle variable not used by value, but used as pointer. Look at this:

i <- 0 
print(p)

i <- 1
print(p)
Yury Arrow
  • 176
  • 7
  • I may make a mistake, but even with `data(LakeHuron)` as preparation your above code fails in my R v3.2.5 with `Error in eval(expr, envir, enclos) : object 'level' not found` - and maybe it would be good for those willing to help, when you in the second sample (debugging the "Pointer hypothesis) You show values you got from the `print(p)` calls. – Dilettant Jun 09 '16 at 16:18
  • 1
    Thanks. print(p) - just plot ggplot graph. Strange, about LakeHuron. in string huron <- data.frame(year = 1875:1972, level = as.vector(LakeHuron)) i create dataframe from time series – Yury Arrow Jun 09 '16 at 16:26
  • I think one bug is `0:count - 1`. This is a sequence that will start at -1. You probably want `0:(count - 1)`. – Gregor Thomas Jun 09 '16 at 16:39
  • Sorry, you right. But this is not a problem – Yury Arrow Jun 09 '16 at 16:45
  • You are running into a problem with ggplot's "lazy evaluation". [This answer](http://stackoverflow.com/a/26246791/2461552) outlines the problem and gives a useful way to work around it. – aosmith Jun 09 '16 at 22:30

1 Answers1

0
p <- ggplot(huron, aes(year))+geom_line(aes(x=year, y=level), color='blue')+theme_bw()
for (i in 0:(count-1))
{
p <- p + 
geom_ribbon(aes_string(ymin=p$data$level-(p$data$level/m)*i, ymax=p$data$level-(p$data$level/m)*(i+1)), alpha=start_alpha-(start_alpha/count)*i, fill='blue')
}
print(p)
Yury Arrow
  • 176
  • 7