Home > other >  How to add several vertical lines to ggplot2 in R?
How to add several vertical lines to ggplot2 in R?

Time:02-01

  df <- tibble(word = c("apple", "apple","banana", "pear","pear","A","A","A","A","A","A","A","A","A"),     i = seq_along(word),year=c(2000,2001,2000,2000,2001,2000,2001,2002,2000,2002,2003,2004,2005,2006))

I can plot it like this:

ggplot(df, aes(year, i))      geom_line()      facet_wrap(~ word)

I want to add vertical lines:

 library(strucchange)
 gft=df%>%filter(word=="A")
 ds <- ts(gft$i, start = 2000, frequency = 1)
 jj=breakdates(breakpoints(ds ~ 1,2))

I did this for "A",How to do this for all other words? And add jj i.e. 2001 2003 2006 to the plot above as vertical lines.

CodePudding user response:

You can use this, just prepare your data for the desired vertical lines.

vlines <- tibble(word = c("apple", "banana", "pear", "A"), lines = c(2000, 2001, 2002, 2004))

ggplot(df, aes(year, i))   geom_line()   facet_wrap(~ word)  
  geom_vline(data = vlines, aes(xintercept = lines, group = word))

CodePudding user response:

To add the breakpoint lines only to the facet of word == "A", create a new data.frame with those break points and a column word. Then use that data.frame in geom_vline.

gftjj <- data.frame(word = unique(gft$word), jj)

ggplot(df, aes(year, i))  
  geom_line()      
  geom_vline(data = gftjj, aes(xintercept = jj))  
  facet_wrap(~ word)

enter image description here

  •  Tags:  
  • Related