I have a data.table that I want to plot
cbo = data.table(date = seq(as.Date("2000/4/2"), by = "week", length.out = 9), week = 1:9, x= sample(10000:50000, 9))
Week 6 to 9 forecasts. I want a dotted line from 2000-05-07 onward to signify the forecasts and shade the background in blue.
My ggplot2
ggplot(cbo)
aes(x = date, y = x)
geom_line(size = 0.5, colour = "#112446")
theme_minimal()
Question: How do I dot the line from week == 6, date = 2000-05-07 and shade background in blue colour to distinguish the forecasted numbers?
CodePudding user response:
I think this should accomplish what you're looking to do. I used geom_rect
to shade the plot and an ifelse
to adjust the linetype in the aes
of geom_segment
. If you just use geom_line
you'll end up with a gap between the dates for week 5 and 6.
library(ggplot2)
library(data.table)
# make data
cbo <- data.table(date = seq(as.Date("2000/4/2"), by = "week", length.out = 9), week = 1:9, x= sample(10000:50000, 9))
# plot data
ggplot(cbo)
geom_segment(aes(x = date, xend = lead(date), y = x, yend = lead(x),
linetype = ifelse(date > as.Date("2000-04-30"), "solid", "dashed")), # adjust linetype
size = 1)
# plot a rectangle
geom_rect(aes(xmin = as.Date("2000-05-07"), xmax = as.Date("2000-05-30"), ymin = min(x), ymax = Inf),
fill = "blue", alpha = 0.1) # adjust alpha for shading
theme_minimal()
theme(legend.position = 'none')
CodePudding user response:
You can plot geom_line
twice. Once with a solid line until week 6 and once with a dotted line for the whole line.
library(tidyverse)
library(data.table)
cbo = data.table(date = seq(as.Date("2000/4/2"), by = "week", length.out = 9), week = 1:9, x= sample(10000:50000, 9))
ggplot(cbo)
aes(x = date, y = x)
geom_rect(aes(xmin = as.Date("2000-05-07"), xmax = as.Date("2000-05-28"), ymin = -Inf, ymax = Inf),
fill = "#6BC6F5FF", alpha = 0.1)
geom_line(size = 0.5, colour = "#112446", lty = 2)
geom_line(data = cbo %>% filter(week <= 6), size = 0.7, color = "#112446", lty = 1)
theme_minimal()