Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shiny: Change column used in ggplot2 dynamically

Tags:

ggplot2

shiny

I tried creating a Shiny app where you can choose the x-Axis of a ggplot per 'selectizeInput'.

I know about the Gallery Example, where this was solved by pre-selecting the desired column. Because in my case the data structure is a bit complex I would prefer, when it is possible to change the x = attribute in aes() dynamically.

For better understanding I added a minimal working example. Unfortunately ggplot uses the input as value, instead to use the corresponding column.

library(shiny)
library(ggplot2)


# Define UI for application that draws a histogram
ui <- shinyUI(fluidPage(

   # Application title
   titlePanel("Select x Axis"),       

   sidebarLayout(
      sidebarPanel(
        selectizeInput("xaxis", 
                       label = "x-Axis",
                       choices = c("carat", "depth", "table"))            
      ),          

      mainPanel(
         plotOutput("Plot")
      )
   )
))

server <- shinyServer(function(input, output) {

   output$Plot <- renderPlot({
     p <- ggplot(diamonds, aes(x = input$xaxis, y = price))
     p <-p + geom_point()
     print(p)
   })
})

# Run the application 
shinyApp(ui = ui, server = server)
like image 842
WitheShadow Avatar asked Jul 18 '16 08:07

WitheShadow


1 Answers

aes uses NSE (non-standard evaluation). This is great for interactive use, but not so great for programming with. For this reason, there are two SE (standard evaluation) alternatives, aes_ (formerly aes_q) and aes_string. The first takes quoted input, the second string input. In this case, the problem can be quite easily solved by using aes_string (since selectizeInput gives us a string anyways).

ggplot(diamonds, aes_string(x = input$xaxis, y = 'price')) +
  geom_point()
like image 152
Axeman Avatar answered Sep 19 '22 14:09

Axeman