使用ggplot突出周末?

lin*_*inp 4 r ggplot2

我没有找到任何有关此问题的历史问题......我想突出显示ggplot图表的周末表现,以便用户可以直接告诉图表哪一部分(可能是灰色阴影?)是周末表现.

这是测试数据的简单版本:

test <- data.frame(DATE=seq(from = as.POSIXct("2014-07-16 01:00"), to = as.POSIXct("2014-07-30 00:00"), by = "hour"),count=floor(runif(336,1,100)))
Run Code Online (Sandbox Code Playgroud)

我的图表的简单版本是:

ggplot() + geom_line(aes(x=DATE,y=count),data=test) + labs(title="test")
Run Code Online (Sandbox Code Playgroud)

所以结果可能像下面的东西......

在此输入图像描述

myn*_*his 7

使用geom_area()更简洁,适用于任何日期范围.

    library(ggplot2)

    test <- data.frame(DATE=seq(from = as.POSIXct("2014-07-16 01:00"), 
                                to = as.POSIXct("2014-07-30 00:00"), 
                                by = "hour"),
                       count=floor(runif(336,1,100)))

    test$weekend <- weekdays(test$DATE) %in% c("Saturday", "Sunday")

    ggplot(data=test, aes(x=DATE, y=count)) +
      geom_area(aes(y=weekend*max(count)), fill="yellow") +
      geom_line() +
      labs(title="test")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


arv*_*000 5

这是在您的数据中执行两个周末的代码.您可以通过添加更多geom_rect()调用(或调用一个循环)来推广到任意数量的周末.

# your data
test <- data.frame(DATE=seq(from = as.POSIXct("2014-07-16 01:00"), to = as.POSIXct("2014-07-30 00:00"), by = "hour"),count=floor(runif(336,1,100)))
your_plot <- ggplot(test) + geom_line(aes(x=DATE,y=count)) + labs(title="test") 

# get all the start and end points
library(lubridate) # for hour function
sats <- which(hour(test$DATE)==0 & weekdays(test$DATE)=='Saturday')
suns <- which(hour(test$DATE)==23 & weekdays(test$DATE)=='Sunday')

# do your plot plus weekend highlights
your_plot +
  geom_rect(aes(xmin=DATE[sats[1]], xmax=DATE[suns[1]],
                  ymin=min(count), ymax=max(count)),
            fill='yellow', alpha=.005) +

  geom_rect(aes(xmin=DATE[sats[2]], xmax=DATE[suns[2]],
                ymin=min(count), ymax=max(count)),
            fill='yellow', alpha=.005)
Run Code Online (Sandbox Code Playgroud)

这是输出