Laorie Laorie - 1 month ago 20
R Question

Using ggplot and geom_rect

I have this 3 time series:


a_ts<-ts(a, start=c(1980, 1), frequency=12)
b_ts<-ts(b, start=c(1980, 1), frequency=12)
c_ts<-ts(c, start=c(1980, 1), frequency=12)

a_series_df["b"] <- b_ts
a_series_df["c"] <- c_ts

To use
function i

melted = melt(a_series_df, id.vars="month")

The plot goes well:

ggplot(data=melted, aes(x=month, y=2*value)) + geom_line(aes(colour = variable))

But when i want a shed plot between these intervals below, it shows this error message:

shade = data.frame(x1=c(1980.333 ,2009.167), x2=c(2007.333 ,2009.667), y1=c(0,3), y2=c(0,4))

ggplot(data=melted, aes(x=month, y=2*value)) + geom_line(aes(colour = variable))+
geom_rect(data=shade, mapping=aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2), color='grey', alpha=0.2)

Error in eval(expr, envir, enclos) : object 'month' not found

What am I missing?


You're missing inherit.aes = FALSE in your geom_rect layer. It's expecting to be able to find all the mapped variables from ggplot initialization unless you tell it not to inherit those aesthetics.

This works:

ggplot(data = melted, aes(x = month, y = 2 * value)) +
    geom_line(aes(colour = variable))+
    geom_rect(data = shade,
              mapping = aes(xmin = x1, xmax = x2, ymin = y1, ymax = y2),
              color = 'grey',
              alpha = 0.2,
              inherit.aes = FALSE)

The first rectangle doesn't show up still because your data for the rectangle has both y1 and y2 as 0 - so it is just a line. The second rectangle is there, but it is very small.

#         x1       x2 y1 y2
# 1 1980.333 2007.333  0  0
# 2 2009.167 2009.667  3  4

Set color for the outline of the rectangle, fill for the fill color of the rectangle.