Plotting for on weekends and weekdays separately from time-series dataset

Viewed 1037

I am looking to create two separate plots for weekdays and weekends from my time-series data set

I have two sets of data, one for temperatures and one for load around a substation. I have averaged them over day intervals Using the mutate and wday functions I have turned each day into days of the week eg. "Mon, Tue" etc. I am having trouble plotting it in ggplot. I am pretty new to R so it might be a simple fix.

#For weekend plot
date <- as.POSIXlt(BDR1DM$day, format = "%Y-%m-%d")
df %>%
  select(day, SSLoad) %>%
  mutate(weekend = wday(day, label = TRUE)) %>%
  filter(wday(day) %in% c(1,7))

day <- as.POSIXlt(HDDsumSS$date, format = "%Y-%m-%d")
date$wday
#day of week for Temp data
dt %>% 
  select(date, Temp) %>%
  mutate(weekend = wday(day, label = TRUE)) %>%
  filter(wday(day) %in% c(1,7))

ggplot() +
  aes(x= dt$Temp, y= df$SSLoad)+
  geom_point(data = subset(df, dayofweek$weekend == c("Sat", "Sun")))

I'm not sure if I am using the subplot right in the ggplot. Does anyone know how to plot for, in this case, weekends only.

2 Answers

Including reproducible data:

library(dplyr)
library(ggplot2)
df <- data.frame(date = sample(seq(as.Date('2018/01/01'), 
as.Date('2019/01/01'), by="day"), 100),
                 SSLoad = runif(100,0,100),
                 Temp = runif(100,70,100))

You can filter with dplyr

df <- df %>%
  filter(weekdays(date)=="Saturday" | weekdays(date)=="Sunday") 

ggplot(df, aes(Temp, SSLoad)) + 
  geom_point()

Or you can subset when you select data in ggplot

df <- df %>%
  mutate(weekend = (weekdays(date)=="Saturday" | weekdays(date)=="Sunday" ))

ggplot(df[df$weekend==T,], aes(Temp, SSLoad)) + 
  geom_point()

First, why are your fields in different dataframes? I don't think ggplot can use two separate dataframes in one plot. Furthermore, any information that is part of the source dataframe has to be specified inside the aes() function, so you shouldn't specify different data inside the geom_point function. For differentiating weekend and weekdays, you can use the filter function of the dplyr package:
df <- df %>% filter(weekdays(date)=="Saturday" | weekdays(date)=="Sunday")

Related