3

First, let's create some fake data:

d <- c("2019-01-01", "2019-01-02", "2019-01-03", "2019-01-04", "2019-01-03", "2019-04-06", "2019-04-03", "2019-05-07", "2019-05-03", "2019-05-03", "2019-05-03", "2019-05-03", "2019-06-03", "2019-06-03", "2019-06-03", "2019-06-03", "2019-06-03", "2019-06-03", "2019-06-03", "2019-07-03", "2019-07-03", "2019-07-04", "2019-08-03", "2019-09-05", "2019-09-03", "2019-09-03", "2019-09-06", "2019-09-08", "2019-10-03", "2019-11-03", "2019-11-03", "2019-11-03", "2019-11-03", "2019-11-03", "2019-11-03", "2019-12-03", "2019-12-03")

df <- data.frame(dates=as.Date(d))

Now, I create a time-series plot:

# aggregate data
df_plot <- df %>% mutate(month = lubridate::floor_date(dates, "month")) %>% 
  group_by(month) %>% summarise(count = n())

# plot data
ggplot(aes(x = month, y = count), data = df_plot) + geom_line() +
  scale_x_date() +
  geom_vline(xintercept = as.numeric(as.Date("2019-01-30")), linetype=4)

With geom_vline(xintercept = as.numeric(as.Date("2019-01-30")), linetype=4) I can mark a certain date with a vertical line. Is there also a possibility to mark a time-range (let's say from 2019-01-30 to 2019-02-15) with a colored box or something?

tjebo
  • 21,977
  • 7
  • 58
  • 94
D. Studer
  • 1,711
  • 1
  • 16
  • 35
  • 2
    http://www.sthda.com/english/wiki/be-awesome-in-ggplot2-a-practical-guide-to-be-highly-effective-r-software-and-data-visualization - look up `geom_ribbon`, there is an example with `geom_rect` – Jonny Phelps Nov 27 '19 at 13:20

1 Answers1

5

Use geom_rect with ymin = -Inf and ymax = Inf.

xmin <- as.Date("2019-01-30")
xmax <- as.Date("2019-02-15")

ggplot(df_plot, aes(month, count)) + 
  geom_line() +
  scale_x_date() +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf, 
    alpha = I(.1), fill  = I("lightblue"))) +
  annotate("text", label = "Some text", x = xmin, y = Inf, angle = 90,
    hjust = 1.1, vjust = -1)

(continued after screenshot)

screenshot

Another possibility is to create a data frame regimes to hold the boundaries and labels. This is similar to the previous code but if we had to add more regimes it would just be a matter of adding rows to regimes.

regimes <- data.frame(xmin = as.Date("2019-01-30"),
                      xmax = as.Date("2019-02-15"),
                      label = "Some text")

ggplot(regimes) + 
  geom_line(aes(month, count), df_plot) +
  scale_x_date() +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), 
    alpha = I(.5), fill = I("lightblue")) +
  geom_text(aes(x = xmin, y = Inf, label = label), angle = 90, 
    hjust = 1.1, vjust = -1)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341