-1

I have plotted water meter averages for different dates. I want to colour the averages which are measured on the weekends? How do I do this please?

plot <- ggplot(DF, aes(Date, Measurement)) +
  geom_point() +
  ggtitle('Water Meter Averages') +
  xlab('Day No') +
  ylab('Measurement in Cubic Feet')

Date <- c("2018-06-25", "2018-06-26", "2018-06-27", "2018-06-28", "2018-06-29", "2018-06-30", "2018-07-01")
Measurement <- c("1","3","5","2","4","5","7")

DF <- data.frame(Date, Measurement)

"2018-06-30" and "2018-07-01" are weekend dates with the corresponding values 5 and 7 respectively. How can I adapt my ggplot code so that R recognizes these dates as weekends and colors the points related to this dates on my ggplot.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
J Nkansa
  • 5
  • 3
  • 2
    It would help if this were a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). In this case, I think providing a sufficient sample of your data using something like `dput(head(DF))` might suffice, though you need to make sure the sample has enough variability in its `Date` to show what you need. An alternative is to contrive a much simpler `data.frame` manually (literally giving us the `data.frame(...)` code) with very specific data points. – r2evans Jul 02 '18 at 18:16
  • @r2evans does it make sense now? – J Nkansa Jul 02 '18 at 18:31
  • Your pasted code was broken in a few ways, I fixed it. – r2evans Jul 02 '18 at 18:57

1 Answers1

1

First, make sure your data values are actually coded as date/time values in R and not strings or factors. Then you can do

# Make sure class(DF$Date)=="Date"
DF <- data.frame(Date=as.Date(Date), Measurement)

ggplot(DF, aes(Date, Measurement, color=weekdays(Date) %in% c("Saturday","Sunday")))+geom_point() +
  ggtitle('Water Meter Averages') +
  xlab('Day No') +
  ylab('Measurement in Cubic Feet') + 
  scale_color_discrete(name="Is Weekend")

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • No, the time before I (was ready to) click submit that I saw your answer posted :-) – r2evans Jul 02 '18 at 19:07
  • No problem at all! No, my solution added a column to the original `DF`, but otherwise looked fairly identical. Team effort. (If I hadn't spent the time to type the code to add the column, perhaps we would have simultaneously-submitted answers. \*shrug\*) – r2evans Jul 02 '18 at 19:09
  • This makes sense. Thank you! – J Nkansa Jul 02 '18 at 19:13