Home > Enterprise >  Dynamic vlines and annotations on ggplot
Dynamic vlines and annotations on ggplot

Time:09-07

I was wondering if it's possible to dynamically generate geom_vlines and annotations for a ggplot based on the contents of another dataframe.

I currently have a dataframe of the following structure, which I use to plot a time-series:

 $ Date : Date, format: "2021-07-02" "2021-07-05" "2021-07-06" "2021-07-07" ...
 $ type : chr  "25 25" "25 25" "25 25" "25 25" ...
 $ dec     : num  -0.193 -0.189 -0.176 -0.195 -0.219

I then use that df to plot a chart:

ggplot(df) geom_line(aes(x=Date, y=type, color=dec)) geom_point(aes(x=Date, y=dec, color=type)) 
  geom_hline(yintercept = 0) geom_vline(xintercept = as.numeric(ymd("2022-08-25")), linetype="dashed", color = "red") 
  geom_vline(xintercept = as.numeric(ymd("2022-07-19")), linetype="dashed", color = "red") geom_vline(xintercept = as.numeric(ymd("2022-04-19")), linetype="dashed", color = "red") annotate(x=as.Date(ymd("2022-08-25")), y= Inf,vjust=1,hjust=2.1,size=3,label="25/08/22 No:1.6", geom="text", angle=90) 
  annotate(x=as.Date(ymd("2022-07-19")), y= Inf,vjust=1,hjust=2.1,size=3,label="19/07/22 No:2.1", geom="text", angle=90) annotate(x=as.Date(ymd("2022-04-19")), y= Inf,vjust=1,hjust=2,size=3,label="19/04/22 No:2.4", geom="text", angle=90)

I currently have to enter both the geom_vlines and corresponding annotations manually, and it's becoming an increasingly unwieldy exercise to complete if a lot of annotations are necessary. I was wondering if it would be possible to dynamically generate these annotations and vlines from another dataframe?

I've been to source and tidy-up this data, and now have it in a dataframe like this:

$ Date     : Date, format: "2022-08-25" "2022-07-19" "2022-04-19" ...
$ Amount  : num  1.6 2.4 2.1 ...

Realise it may be a bit 'out there' but any advice/assistance is greatly appreciated.

CodePudding user response:

With thanks to Jon Spring, it's now working as intended. Using:

ggplot(df) geom_line(aes(x=Date, y=type, color=dec)) geom_point(aes(x=Date, y=dec, color=type)) 
  geom_hline(yintercept = 0) 
  geom_vline(data = df2, aes(xintercept = Date), linetype="dashed", color = "red") geom_text(data = df2, aes(x = Date, y = Inf, label = Date), vjust=1,hjust=2.1,size=3,angle=90)
  • Related