1

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?

ERT
  • 719
  • 5
  • 16
  • Have you seen this https://stackoverflow.com/questions/45331314/plot-a-vertical-line-at-the-minimum-maximum-value-in-a-time-series-plot ? – RLave Jul 19 '18 at 13:24
  • Also you should post an example of your data to help with the answer. – RLave Jul 19 '18 at 13:25
  • @RLave yes, I know I can use the `plot.zoo()` function, but since my data is in `xts` format it would be much easier to plot using the built-in `plot.xts()` – ERT Jul 19 '18 at 13:32

1 Answers1

3

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")
shadow
  • 21,823
  • 4
  • 63
  • 77
  • 1
    This is a nice solution, if it is acceptable to create another entire data series. I actually broke down and regressed to using `plot.zoo()` as I had done in the past. It takes significantly longer to set up, but is much better for customization. The function is able to interact with other built-in functions (`legend`, `abline`, etc.). – ERT Jul 24 '18 at 15:00