Search code examples
rplotxts

Add Horizontal Line to xts Plot


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?


Solution

  • 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")