[R] Add a vertical arrow to a time series graph using ggplot and xts

jpm miao miaojpm at gmail.com
Mon Apr 18 22:28:10 CEST 2016


Hi,

   I am trying to add a vertical arrow (from top to bottom or from bottom
to up) to a time series plot using ggplot2 and xts. It seems that the
vertical line command "geom_vline" does not work for this purpose (Correct
me if I am wrong). I try the command "geom_segment" as follows, but I got
an error message at the last line "Error: Invalid input: date_trans works
with objects of class Date only".

    Sometimes the error message occurs when I run the program, sometimes it
does not occur until I call the plot "p1". How could I add a vertical line
to the plot? Thanks!

Miao


######################
library(xts)  # primary
#library(tseries)   # Unit root tests
library(ggplot2)
library(vars)
library(grid)
dt_xts<-xts(x = 1:10, order.by = seq(as.Date("2016-01-01"),
as.Date("2016-01-10"), by = "1 day"))
colnames(dt_xts)<-"gdp"
xmin<-min(index(dt_xts))
xmax<-max(index(dt_xts))
df1<-data.frame(x = index(dt_xts), coredata(dt_xts))
p<-ggplot(data = df1, mapping= aes(x=x, y=gdp))+geom_line()
rg<-ggplot_build(p)$panel$ranges[[1]]$y.range
y1<-rg[1]
y2<-rg[2]
df2<-data.frame(x = "2016-01-05", y1=y1, y2=y2 )
p1<-p+geom_segment(mapping=aes(x=x, y=y1, xend=x, yend=y2), data=df2,
arrow=arrow())

	[[alternative HTML version deleted]]



More information about the R-help mailing list