Reputation: 623
I need to visualize data from a weather station across ~3 months. During the season, gas sampling in the ground was performed on 5 specific dates. I would like to highlight these dates in the graph with weather station data.
I am trying to accomplish this by placing grey bars on the geom_point
ggplot
I have made
p <- ggplot(ws_may_sep_plot, aes (x = date_time, y = temperature)) +
geom_point(size=0.5) +
scale_x_datetime(breaks = "2 week")
ggtitle("Ambient temperature")
may_start <- "2012-05-22"
may_start_iso <- as.Date(may_start)
may_end <- "2012-05-23"
may_end_iso <- as.Date(may_start)
rect <- data.frame(xmin= may_start_iso, xmax= may_end_iso, ymin=-Inf,
ymax=Inf)
p + geom_rect(data=rect, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax),
color="grey20",
alpha=0.5,
inherit.aes = FALSE)
Here is a link to the data: https://www.dropbox.com/s/2z0branzp7r26gl/highlighting%20dates.R?dl=0
glimpse(ws_may_sep_plot)
Observations: 2,209
Variables: 8
Groups: rh, precipitation, temperature, par [2,203]
$ date_time <dttm> 2012-05-15 00:00:00, 2012-05-15 01:00:00, 2012-05-15 02:00:00, 2012-05-15 03:00:00, 201...
$ temperature <dbl> 3.1, 2.3, 3.3, 4.1, 5.1, 7.1, 8.1, 7.7, 8.0, 9.5, 11.0, 10.7, 9.9, 9.6, 9.6, 10.1, 9.9, ...
When I run my code I receive the following error:
Invalid input: time_trans works with objects of class POSIXct only
Upvotes: 1
Views: 919
Reputation: 2368
USe scale_x_date("2 week")
instead of scale_x_datetime
. Your dates are only dates not datetimes (time component with date).
df <- data.frame(date = seq.Date(as.Date("2012-01-01"), as.Date("2012-07-01"), by = "day"),
temperature = rnorm(183, 30, 1))
p <- ggplot(df, aes (x = date, y = temperature)) +
geom_point(size=0.5) +
#scale_x_datetime(breaks = "2 week")
ggtitle("Ambient temperature")
may_start <- "2012-05-22"
may_start_iso <- as.Date(may_start)
may_end <- "2012-05-23"
may_end_iso <- as.Date(may_start)
rect <- data.frame(xmin= may_start_iso, xmax= may_end_iso, ymin=-Inf,
ymax=Inf)
p + geom_rect(data=rect, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax),
color="grey20",
alpha=0.5,
inherit.aes = FALSE)+
scale_x_date(breaks = "2 week") # Should work!
Upvotes: 2