I am trying to do something like https://stackoverflow.com/a/29649406/15485 but I get the error
Error: Aesthetics must be either length 1 or the same as the data (2): xmin, xmax, ymin, ymax, x, y
What does '(2)' means?
What 'Aesthetics' are involved? I have aes
in ggplot
and aes
in geom_rect
but I have no idea about how to correct them... I am afraid I will never grasp ggplot
...
days<-rep(Sys.Date(),100)+seq(1,100)
v<-sin(as.numeric(days))
df<-data.frame(days=days,v=v)
shade <- data.frame(x1=c(as.Date('2017-10-15'),as.Date('2017-11-11')),
x2=c(as.Date('2017-10-20'),as.Date('2017-11-13')),
y1=c(-Inf,-Inf), y2=c(Inf,Inf))
library(ggplot2)
plot(ggplot(df,aes(x=days,y=v))
+geom_line()
+geom_rect(data=shade,
mapping=aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2), color='grey', alpha=0.2)
+geom_point())
The geom_rect
line was trying to inherit default aesthetics from the top line ggplot(df, aes(x = days, y = v))
.
The following would work:
ggplot(df, aes(x=days, y=v)) +
geom_line() +
geom_rect(data=shade, inherit.aes = F,
aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2),
color = 'grey', alpha=0.2) +
geom_point()
(I added more line breaks / spaces into the code for easier reading. Also, there's no need to wrap the whole ggplot object in plot()
.)