I would like to reproduce the following plot, but I would like to add date labels every 4 months instead of numeric.
I had to convert the date_time values to numeric in order to plot the annotate("rect")
as I wanted it to extend the length of the rectangle to the edge of the plot, similar to geom_hline
. I found the annotate
approach the quickest. I now have an issue, as I would like to have date labels on the x axis instead of numeric.
I have tried using scale_x_continuous
but this took too long and doesn't seem to work.
Thanks for your help.
# Reproducible data
set.seed(123)
start_date_time <- as.POSIXct("2023-07-01 00:00:00")
end_date_time <- as.POSIXct("2023-07-02 00:00:00")
date_time <- seq(from = start_date_time, to = end_date_time, by = "15 min")
depth <- runif(length(date_time), min = 0, max = 0.5)
df <- data.frame(date_time = date_time, depth = depth)
df$N_dt <- as.numeric(df$date_time)
x_point <- min(df$N_dt)
full_level <- 0.4
pipe_bottom <- 0.15
pipe_top <- 0.35
pipe <- 0.25
df %>%
ggplot(aes(x = N_dt,
y = depth)) +
geom_line(size = 0.25) +
labs(x = "Date",
y = "Water level (m)") +
geom_hline(yintercept = full_level, linetype = 'dashed',
color = 'black') +
annotate("text", x = x_point, y = (full_level + 0.03),
label = "Full level", size = 8 / .pt) +
annotate("text", x = x_point, y = pipe,
label = "Pipe", size = 8 / .pt) +
annotate("rect", xmin = -Inf, xmax = Inf,
ymin = pipe_bottom, ymax = pipe_top, alpha = .1) +
theme_classic() +
theme(
plot.title = element_blank(),
axis.text = element_text(size = 8),
axis.title = element_text(size = 8.5),
legend.title = element_blank(),
legend.position = "top",
panel.border = element_rect(color = "black", fill = NA)
)