[英]How to add several vertical lines to ggplot2 in R?
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))
我可以像這樣 plot 它:
ggplot(df, aes(year, i)) + geom_line() + facet_wrap(~ word)
我想添加垂直線:
library(strucchange)
gft=df%>%filter(word=="A")
ds <- ts(gft$i, start = 2000, frequency = 1)
jj=breakdates(breakpoints(ds ~ 1,2))
我為“A”做了這個,如何為所有其他單詞做這個? 並將 jj ie 2001 2003 2006
添加到上面的 plot 作為垂直線。
您可以使用它,只需為所需的垂直線准備數據。
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))
您可以通過創建具有兩列的 dataframe 來實現所需的結果。 第一列包含xintercept
的值,第二列包含要放置 vline 的word
:
library(ggplot2)
jj_A <- c(2000, 2002)
jj_pear <- c(2004, 2005, 2006)
df_vline <- data.frame(
x = c(jj_A, jj_pear),
word = c(rep("A", 2), rep("pear", 3))
)
ggplot(df, aes(year, i)) +
geom_line() +
geom_vline(data = df_vline, aes(xintercept = x)) +
facet_wrap(~word)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.