Add Horizontal Line to xts Plot

2019-08-21 09:57发布

问题:

I would like to add a horizontal line to an xts object plot. I know there is the addEventLines() function in xts to add vertical lines, but the following does not add a line to an xts plot:

abline(h=abc, col="green")

Is there a workaround for this other than adding a new column to the object itself before plotting?

回答1:

You can just create some constant data and use the lines function. Below is a solution together with a reproducible example.

# load package
require(xts)

# get data
data(sample_matrix)
sample.xts <- as.xts(sample_matrix)

# create line data
sample.xts$horizontal_line <- 49.5

# plot 
plot(sample.xts[,"Close"])
lines(sample.xts[, "horizontal_line"], col = "blue")


标签: r plot xts