5

I want to plot rectangle "shading" in with my ggplot. The ggplot code works and provides the image shown below. I looked for information here and constructed a data frame for the x and y values.

mydf<-data.frame(tiempo=df5$tiempo,vel=df5$TR2x45.17)[1:14,]
structure(list(tiempo = c(618.2, 618.4, 618.6, 618.8, 619, 619.2, 
619.4, 619.6, 619.8, 620, 620.2, 620.4, 620.6, 620.8), vel = c(0, 
0, -4, -9, 5, 9, 1, 4, 0, 0, -1, -4, 0, 1)), .Names = c("tiempo", 
"vel"), row.names = c(NA, 14L), class = "data.frame")

rects <- data.frame(xstart = seq(618,619.5,.5), xend = seq(618.5,620,.5), col = letters[1:4])

ggplot(data=mydf,
       aes(x=tiempo,y=vel))+theme_minimal()+
           geom_point(size=4)+
    labs(title=c("Velocidad ejemplo pasaje figura"))+
       geom_smooth(method="loess", span=.3, se=FALSE, colour="red", size=1,alpha=0.5) +
geom_rect(data = rects, aes(xmin = xstart, xmax = xend, ymin = -Inf, ymax = Inf, fill = col), alpha = 0.4) 

If I run the code until the geom_smooth(...) line produces the plot. If I add geom_rect(...) it gives this error back: Error in eval(expr, envir, enclos) : object 'tiempo' not found

enter image description here

I don't understand what does it mean that "tiempo" is not being found while everyother thing finds it. Also, I'm using another dataframe with geom_rect() so why is it looking for tiempo there?

Community
  • 1
  • 1
Matias Andina
  • 4,029
  • 4
  • 26
  • 58

1 Answers1

5

OK. This:

geom_rect(inherit.aes = FALSE, data = rects, aes(xmin = xstart, xmax = xend, ymin = -Inf, ymax = Inf, fill = col), alpha = 0.4)
lnNoam
  • 1,055
  • 11
  • 20
  • Just a remark in passing: `-Inf` fails when using a logscale. Not sure what the workaround would be yet. – PatrickT Feb 02 '22 at 23:56