user1471980
user1471980

Reputation: 10626

Create a shaded area in ggplot chart

My data frame called cpu:

structure(list(Date = structure(c(15229, 15236, 15243, 15250, 
15257, 15264, 15271, 15278, 15285, 15292, 15299, 15306, 15313, 
15320, 15327, 15334, NA, 15341, 15348, 15355, 15362, 15369, 15376, 
15383, 15390, 15397, 15404, 15411, 15418, 15425), class = "Date"), 
    Pc = c(13.28, 8.96, 11.68, 9.76, 9.6, 9.92, 8.48, 10.56, 
    12, 14.08, 10.72, 12, 11.04, 11.68, 11.52, 12.64, 5.6, 11.84, 
    11.84, 11.36, 11.84, 13.28, 12.16, 12.64, 12.48, 13.28, 11.36, 
    11.2, 11.04, 12.16)), .Names = c("Date", "Pc"), row.names = c(4974L, 
5009L, 5044L, 5068L, 5203L, 5238L, 5093L, 5103L, 5138L, 5173L, 
5446L, 5481L, 5516L, 5551L, 5586L, 5298L, 5328L, 5333L, 5368L, 
5403L, 5596L, 5631L, 5666L, 5821L, 5856L, 5691L, 5726L, 5756L, 
5791L, 6066L), class = "data.frame")

I need to create shade areas in the chart by using geom_rect. I have the following:

 ggplot(cpu, aes(Date, Pc, group=1)) + 
    geom_point() + 
    geom_smooth(method="loess", size=1, colour="blue") + 
    theme_bw() + 
    scale_x_date(breaks = "3 weeks",minor_breaks="1 weeks",labels=date_format("%m/%d/%y")) + 
    theme(axis.text.x = element_text(angle=60, hjust=1)) + 
    geom_rect(data=cpu,aes(xmin=as.Date(c("2011-10-10")), xmax=as.Date(c("2013-08-11")), ymin=0, ymax=Inf))

Shaded area overlaps the dots and I cannot see the dots. How could I do this so that I also see the geom_points behind the geom_rect area?

Upvotes: 1

Views: 1077

Answers (1)

joran
joran

Reputation: 173527

As I said in my original comment, this works for me:

ggplot(cpu, aes(Date, Pc, group=1)) + 
    geom_rect(data=cpu,xmin=as.numeric(as.Date(c("2011-10-10"))), 
        xmax=as.numeric(as.Date(c("2013-08-11"))), ymin=0, ymax=Inf,fill = "blue",alpha = 0.01) +
    geom_point() + 
    geom_smooth(method="loess", size=1, colour="blue") + 
    theme_bw() + 
    scale_x_date(breaks = "3 weeks",minor_breaks="1 weeks",labels=date_format("%m/%d/%y")) + 
    theme(axis.text.x = element_text(angle=60, hjust=1))

I think something else may be going on with the geom_rect layer, because I shouldn't need an alpha level that small, so I'm worried about inadvertent overplotting. But I have to run to a meeting now. If anyone spots the problem, feel free to comment/edit.

Upvotes: 2

Related Questions