Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
971 views
in Technique[技术] by (71.8m points)

ggplot2 - R - How do I use selectInput in shiny to change the x and fill variables in a ggplot renderPlot?

I'm trying to make an interactive shiny dashboard that has an interactive plot where you can change the values of the plot. The code chunk that I'm putting inside of renderPlot works normally, so I don't understand why count isn't showing on the y axis when I use selectInput to change the X and Fill variables.

 inputPanel(
  selectInput('x', 'X', names(data)),
  selectInput('y', 'Y', names(data))
)

renderPlot({
    ggplot(data, aes(x = input$x)) +
  geom_bar(aes(fill = input$y), position = position_stack(reverse = TRUE)) +
 coord_flip() + 
 theme(legend.position = "top")
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason is that the input$x and input$y are character class. So, instead of aes, use aes_string

renderPlot({
  ggplot(data, aes_string(x = input$x)) +
  geom_bar(aes_string(fill = input$y), position = position_stack(reverse = TRUE)) +
  coord_flip() + 
  theme(legend.position = "top")
})

A reproducible example with data(mpg)

library(shiny)
library(ggplot2)


data(mpg)

ui <- fluidPage(
  inputPanel(
    selectInput('x', 'X', choices = c("manufacturer", "model", "year", "cyl", "class"),
          selected = "class"),
    selectInput('y', 'Y', choices = c( "trans", "fl", "drv"), 
  selected = "drv")
  ),

  mainPanel(plotOutput("outplot"))

)

server <- function(input, output) {

  output$outplot <- renderPlot({
    ggplot(mpg, aes_string(x = input$x)) +
      geom_bar(aes_string(fill= input$y), position = position_stack(reverse = TRUE)) +
      coord_flip() + 
      theme(legend.position = "top")
  })

}

shinyApp(ui = ui, server = server)

-output

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...