改变周末积分的颜色

时间:2018-07-02 18:08:09

标签: r dataframe ggplot2

我绘制了不同日期的水表平均值。我要为周末测量的平均值上色吗?我该怎么做?

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”和“ 2018-07-01”是周末日期,分别具有相应的值5和7。如何调整ggplot代码,以便R将这些日期识别为周末,并在ggplot上为与该日期相关的点着色。

1 个答案:

答案 0 :(得分:1)

首先,请确保您的数据值实际编码为R中的日期/时间值,而不是字符串或因子。那你可以做

# 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