【问题标题】:Problem passing variable names via selectInput() in R/Shiny在 R/Shiny 中通过 selectInput() 传递变量名的问题
【发布时间】:2019-05-22 14:59:25
【问题描述】:

我正在构建一个闪亮的应用程序,其中我使用 selectInput() 小部件将变量名称作为参数传递给服务器。以下静态示例说明了我想要显示的图:

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

为了清楚起见,这里是image of the above plot

我想要在我的 shinyapp 中做的是通过用户可以通过 selectInput() 选择的不同变量来分隔绘制的分布。但是当我用通用参数替换上面的 var1 时,这不是我得到的。请看示例:

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)

我得到的实际输出是 different from the static example 我从(点击查看图片)开始。

有人可以指出我的错误吗?感谢您的帮助。

【问题讨论】:

    标签: r ggplot2 shiny selectinput


    【解决方案1】:

    input$var 是一个字符串。因此,做

    output$plot <- renderPlot({
      g <- ggplot(d, aes_string("y", fill = input$var, colour = input$var)) + 
             geom_density(alpha=.2)
      g
    })
    

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 2018-06-22
      • 2023-04-02
      • 2019-12-19
      • 2021-08-04
      • 2015-05-12
      • 2021-08-11
      • 1970-01-01
      • 2019-03-28
      相关资源
      最近更新 更多