Mercury Darmstadium
Mercury Darmstadium

Reputation: 35

Rendering a ggplot2 object using a custom function and renderPlot()

I have been having trouble with visualizing a ggplot. When I run the following code, all I get is a blank screen, but no error messages:

library(ggplot2)
library(shiny)

if (interactive()) {
  ui <-{plotOutput(outputId = "main_plot", height = "300px")}

  server <- function(input, output){
    plotInput <- reactive({ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()})

    output$main_plot <- renderPlot(expr=function(){
      #conditional statements
      plotInput()}
    )

  }
  shinyApp(ui, server)
}

If you run the exact same code without the function definition, however, the plot shows up. I am very perplexed because the documentation of renderPlot permits the use of expressions:

if (interactive()) {
  ui <-{plotOutput(outputId = "main_plot", height = "300px")}

  server <- function(input, output){
    plotInput <- reactive({ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()})

    output$main_plot <- renderPlot(plotInput())

  }
  shinyApp(ui, server)
}

This is a bit of a problem, since I would like to run some conditional statements that determine whether or not to show the plot. Am I using the right approach?

Upvotes: 0

Views: 314

Answers (1)

MrFlick
MrFlick

Reputation: 206197

The expr= of rennderPlot() should be an expression. You are passing a function. Those aren't the same. Try taking off the function() part.

library(ggplot2) library(shiny)

if (interactive()) {
  ui <- plotOutput(outputId = "main_plot", height = "300px")

  server <- function(input, output){
    plotInput <- reactive({ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()})

    output$main_plot <- renderPlot(expr={
      #conditional statements
      plotInput()}
    )

  }
  shinyApp(ui, server)
}

Upvotes: 1

Related Questions