首页 > 解决方案 > 如何根据高峰和非高峰时间在 R 中对我的图进行颜色编码?

问题描述

. 我首先创建了我的数据框 DF。

date <- c("2018-06-25", "2018-06-25", "2018-06-26", "2018-06-26", "2018-06-27", "2018-06-27")

time <- c("10:11:11","17:30:30","15:55:00","18:35:30", "09:06:01","20:15:30")

temperature <- c("15", "18", "16", "17", "14", "15")

DF <- data.frame(date, time, temperature)

DF$Date_Time <- paste(DF$date, DF$time)

DF$Date_Time <- ymd_hms(DF$Date_Time)

. 我想绘制不同日期时间的温度。

. 我想根据高峰和非高峰时间为绘图点着色。上午 9 点到下午 5 点是高峰时间,在这种情况下,任何其他时间都包括非高峰时间。

. 我不确定如何调整下面的代码以便对绘图上的点进行颜色编码。有人可以给我建议吗?

ggplot(DF, aes(Date_Time, temperature))+geom_point() + ggtitle('Temperature plot')

标签: rdatetimedataframeggplot2

解决方案


也许这会有所帮助:

DF$time_test <- ifelse('09:00:00' < time & time< '17:00:00',1,0)


ggplot(DF, aes(Date_Time, temperature, color = time_test))+ geom_point()  + ggtitle('Temperature plot')

或使用data.table

DF$time_test <- between(as.ITime(DF$Date_Time),as.ITime("09:00:00"),as.ITime("17:00:00"))

ggplot(DF, aes(Date_Time, temperature, color = time_test))+geom_point()  + ggtitle('Temperature plot')

您可以使用以下方法更改颜色:scale_color_manual


推荐阅读