6

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)
2
  • Use aes_ or aes_string, see ?aes_. It would become ggplot(diamonds, aes_string(x = input$xaxis, y = 'price')). Commented Jul 18, 2016 at 8:35
  • 1
    Works perfectly, didn't kown about aes_(). If you post it as an answere I will mark it as correct. Thank you. Commented Jul 18, 2016 at 9:06

1 Answer 1

8

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()
Sign up to request clarification or add additional context in comments.

1 Comment

As aes_string is becoming deprecated, the it's good to know about the alternatives !!as.symbol() and !!rlang:sym() as listed in this answer stackoverflow.com/a/60627768/2166823

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.