Maurice
Maurice

Reputation: 119

Plot changing with one or more parameters in R-Shiny

I have little to no experience with R-Shiny, but I thought that I could get it done with a simple example. Used the book Mastering Shiny by Wickham, but I seem to not be able to get this to work.

I am basically trying to do a very simple thing: I would like to produce a plot that depends on a (shape) parameter. My code is the following (simplified to the essence of it):

library(sn)
library(ggplot)

ui <- fluidPage(
  numericInput("a", label = "alpha", min = -3, max = 3, value = 0.0),
  plotOutput("plot")

)

server <-function(input, output, session){
  alpha = reactive(input$a)
  x  <- seq(-4, 4, 0.1)
  y1 <- dsn(x, 0, 1.2, alpha)

  df <- data.frame(x, y1)
  
  output$plot <-renderPlot({
    ggplot(df, aes(x))+
    geom_line(aes(y=y1), size=1.0, color="black")
  }   
    )
}

shinyApp(ui, server)

It is a very simple code, but I keep getting this error message

Listening on http://xxxxxxxxxxxxxxxx
Warning: Error in abs: non-numeric argument to mathematical function
  50: dsn
  49: server [#7]
Error in abs(alpha) : non-numeric argument to mathematical function

I have been trying to solve this issue for at least one day, but to no avail. I would truly appreciate if any kind soul could tell me what I am doing wrong.

Thank you

Maurice.

Upvotes: 1

Views: 126

Answers (1)

jpdugo17
jpdugo17

Reputation: 7106

The object alpha is reactive, so it should be called with parenthesis, alpha(). Also because alpha is a reactive, it needs to be called within reactive context, for example inside observe, reactive or render functions.

App:

library(sn)
library(ggplot)

ui <- fluidPage(
  numericInput("a", label = "alpha", min = -3, max = 3, value = 0.0),
  plotOutput("plot")
)

server <- function(input, output, session) {
  df <- reactive({
    alpha <- as.numeric(input$a)
    x <- seq(-4, 4, 0.1)
    y1 <- dsn(x, 0, 1.2, alpha)

    data.frame(x, y1)
  })


  output$plot <- renderPlot({
    ggplot(df(), aes(x)) +
      geom_line(aes(y = y1), size = 1.0, color = "black")
  })
}

shinyApp(ui, server)

Upvotes: 1

Related Questions