0

Below is functioning code for a basic shiny app that allows the user to pick a column and then plots a ggplot::histogram() of the selected column:

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(
  titlePanel("ggplot"),
  sidebarLayout(
    sidebarPanel(
      uiOutput("column_select")
    ),
    mainPanel(plotOutput("plot"))
  )

)

# Define server logic required to draw a histogram
server <- function(input, output){
  dat <- reactive({iris})
  output$column_select <- renderUI({selectInput("col", label = "column", choices = as.list(names(iris)), selected = "Sepal.Length")})
  output$plot <- renderPlot({ggplot(dat(), aes_string(x = input$col)) +
      geom_histogram()})


  p <- ggplot(dat(), aes_string(x = input$col)) +
    geom_histogram()

  renderPlot
}

# Run the application 
shinyApp(ui = ui, server = server)

I am not sure, however, why I am unable to remove the ggplot() function from within renderPlot() and still get the same result. I have tried:

p <- reactive({ggplot(dat(), aes_string(x = input$col)) +
    geom_histogram()})

  outputPlot <- renderPlot({p})

But this results in no plot being drawn.

I assume there is a simple fix to this, but thus far it escapes me.

Kevin Burnham
  • 553
  • 2
  • 13
  • Why do want to remove the plot from `renderPlot()`? – Haboryme Nov 08 '16 at 17:54
  • @Haboryme I guess I am just trying to understand how it works. Also, what if my ggplot object were coming from a list? I thought the answer to this might help me. – Kevin Burnham Nov 08 '16 at 18:01
  • `renderPlot` allows you to create a plot object that is stored in `output$plot `which is then called in the ui part of the app: `mainPanel(plotOutput("plot")` . I'm not a shiny expert but it doesn't seem to be a good idea to remove the plot from this function. `ggplot` works with dataframes, don't forget that if you plan to use lists. – Haboryme Nov 08 '16 at 18:06
  • 1
    `p` is a reactive, so you need to use it like a function `p()`. So `renderPlot(p())` – Xiongbing Jin Nov 08 '16 at 21:17
  • Yes. Thank you @Xiongbing Jin – Kevin Burnham Nov 09 '16 at 15:13

0 Answers0