RL_Pug
RL_Pug

Reputation: 887

How to manually add a geom_vline() when my x-axis is a factor? R ggplot

I have this graphic

Month2 <- c("Oct 20", "Nov 20", "Dec 20", "Dec 20", "Jan 21", "Feb 21", "Mar 21", "Apr 21", "May 21", "Jun 21")

Forcast_data <- data.frame(
  "Month" = c("Oct 20", "Nov 20", "Dec 20", "Dec 20" ,"Jan 21", "Feb 21", "Mar 21", "Apr 21", "May 21", "Jun 21"),
  "Value" = c(68,47,55, 55, 105, 95,75, 65,60,105),
  "Type" = c("Actual", "Actual", "Actual", "Forecast", "Forecast","Forecast","Forecast","Forecast","Forecast","Forecast")
)

ggplot(Forcast_data, aes(Month2,Value, color=factor(Type))) + 
  geom_line(aes(group = 1)) + 
  geom_point() + 
  scale_x_discrete(limits = Month2) +
  scale_color_manual(values = c("dodgerblue", "orange")) +
  scale_size_manual(values = c(1, 2)) +
  labs(x = "Month") + theme(legend.title = element_blank()) + theme_minimal())

My Goal is to add a dashed line between "Dec 20" and "Jan 21" to indicate its a new year.

I just can't figure out how to manually set my xintercept. Also, the reason I have both a actual & forecast for Dec 20 is because I'm wrapping this graphic in a plotly() and it breaks the lines apart if I don't do it like this. I'm not sure if there is another solution for that.

enter image description here

Upvotes: 2

Views: 311

Answers (1)

Justin Cocco
Justin Cocco

Reputation: 389

Some questions regarding your code: you specify a Month2 component in the graph but you are mapping from the Forcast_data dataframe, and it seems as though that is just a reference so I would recommend loosing that.

Then, I changed your dates to actual dates using lubridate package:

Forcast_data %>% 
  mutate(day = 1) %>% 
  unite(., "date", c(Month, day), sep = "-") %>% 
  mutate(date = myd(date)) -> Forcast_data

The easiest way to do that is to create a day column and then combine them and then use lubridate to turn into a date.

Then I removed:

 #scale_x_discrete(limits = date) +
  #scale_color_manual(values = c("dodgerblue", "orange")) +
  #scale_size_manual(values = c(1, 2)) +

I wasn't sure what value it added; at least to the ggplot aspect. Then used geom_vline() to add your line:

ggplot(Forcast_data, aes(date,Value, color=factor(Type))) + 
  geom_line(aes(group = 1)) + 
  geom_point() + 
  geom_vline(xintercept = as.numeric(as.Date("01/01/2021", format = "%m/%d/%Y"))) +
  labs(x = "Month") + theme(legend.title = element_blank()) + theme_minimal()

which produced Graph output

Upvotes: 2

Related Questions