0

I'm trying to add a horizontal line to a plot within a renderPlot Shiny function. When I add the abline command for the horizontal line, the plot does not render and I see just a horizontal line.

If I remove the abline command, the plot works as expected. I've tried adding the parameter 'new = FALSE' to the abline command, with the same result. I see other examples in SO where it appears to work, but I cannot get it to function properly.

library(shiny)
library(quantmod)
library(TTR)

# UI
ui <- pageWithSidebar(

  # App title ----
  headerPanel("Test Plot with Lines"),

  # Sidebar panel for inputs ----
  sidebarPanel(
    textInput (inputId = "ticker",label = "Ticker Symbol",value="SPY")),

  # Main panel for displaying outputs ----
  mainPanel(
    plotOutput(outputId = "mainPlot")
  )
)

# Server logic
server <- function(input, output) {

  OHLCData <- reactive ({
    tickerData <- get(getSymbols(input$ticker))
    return (tickerData)
  })

  output$mainPlot <- renderPlot ({
    tickerData <- OHLCData()
    meanOpeningPrice <- mean(tickerData[,1])
    plot (tickerData[,1],main=paste(input$inputId,' Opening Price'))
    abline (h=meanOpeningPrice,col='red',new=FALSE)
  })
}

shinyApp(ui, server)

I expect to get a plot of the daily opening price with a red horizontal line at the mean price. Instead I get just a red horizontal line with no axes nor plot of the price.

S Novogoratz
  • 388
  • 2
  • 14
  • I usually use ggplot or plotly in shiny, but I think in base R there is a canvas where plot elements appear. Perhaps this canvas does not exist in shiny, or you have to create it explicitly. – Simon Woodward Sep 19 '19 at 23:45
  • Here's a way of doing it: https://stackoverflow.com/questions/27068854/how-to-add-parts-to-graph-one-by-one-in-shiny – Simon Woodward Sep 19 '19 at 23:50
  • It looks like the you have to provide the different plot element as a `list` in renderPlot. – Simon Woodward Sep 19 '19 at 23:54

1 Answers1

2

How about using lines instead of abline:

tickerData$horizontal_line <- meanOpeningPrice
lines(tickerData[, "horizontal_line"], col = "red")

Seems to be a problem using abline with plot.xts:

How to plot simple vertical line with abline() in R?

https://github.com/joshuaulrich/xts/issues/47

Ben
  • 28,684
  • 5
  • 23
  • 45