1

I'm building a shinyapp where I am passing variable names as arguments to the server with the selectInput() widget. The following static example illustrates the plot that I want displayed:

  g <- ggplot(d, aes(y, fill = var1, colour = var1)) + 
    geom_density(alpha=.2) 

Just to be clear, here is an image of the above plot

What I want to do in my shinyapp is to separate the plotted distributions by different variables that the user can choose via selectInput(). But when I substitute var1 in the above with a generic argument, this is not what I get. Please see the example:

library(ggplot2)
library(shiny)

d <- data.frame(var1=as.factor(sample(x = 1:4, size = 250, replace = TRUE)),
                var2=as.factor(sample(x = 1:4, size = 250, replace = TRUE)),
                y=rnorm(250, mean = 0, sd = 1))

nms <- names(d)

ui <- fluidPage(selectInput(inputId ="var", "Variable:",
                            choices = nms, selected = "var1"),
                plotOutput(outputId = "plot")
)

server <- function(input, output) {

  g <- ggplot(d, aes(y, fill = input$var, colour = input$var)) + 
    geom_density(alpha=.2) 


  output$plot <- renderPlot(g)

}

shinyApp(ui,server)

The actual output I get is different from the static example I started with (click through for image).

Can someone please point out my error? Thankful for help.

1 Answer 1

1

input$var is a string. Therefore, do

output$plot <- renderPlot({
  g <- ggplot(d, aes_string("y", fill = input$var, colour = input$var)) + 
         geom_density(alpha=.2)
  g
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.