Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

r - How can I add a vertical abline for a graf using ggplot with time series data?

I have been trying to add a vertical abline for the 2020-10-13 for the following graf: However, it doesn't show up in the graf.

Graf

I used the following line of code in which I specify the abline using geom_vline:

p_line <-  ggplot(df_total,aes(x=date, y =count,group=sentiment)) +
  geom_line(aes(color=sentiment,linetype=sentiment)) +
  scale_color_manual(values=c("red","blue","springgreen4")) +
  geom_vline(xintercept=2020-10-13  
             , linetype="dashed", color = "red")

See a preview of the dataset below:

Dataset

What am I doing wrong? Does anyone have suggestions?

I have googled, and found different solutions but none work for me :/

question from:https://stackoverflow.com/questions/65901512/how-can-i-add-a-vertical-abline-for-a-graf-using-ggplot-with-time-series-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to wrap the date in your geom_vline into an as.Date:

geom_vline(xintercept=as.Date("2020-10-13"), linetype="dashed", color = "red")

The full code (with some simulated data to reproduce your graph - please next time consider sharing your data with a short dput() command):

df_total <- tibble(date = seq.Date(from = as.Date("2020-10-01"),as.Date("2020-10-24"), by = "day"),
                   neutral = rnorm(24),
                   positive = rnorm(24),
                   negative = rnorm(24))

df_total %>% 
  pivot_longer(-date, "sentiment", values_to = "count") %>% 
  ggplot(aes(x=date, y =count,group=sentiment)) +
  geom_line(aes(color=sentiment,linetype=sentiment)) +
  scale_color_manual(values=c("red","blue","springgreen4")) +
  geom_vline(xintercept=as.Date("2020-10-13"), linetype="dashed", color = "red")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...