R-在Shinny应用中将选项null包含在SelectInput小部件中



我遇到了一些工作中的一些问题。为了解决问题,我正在以钻石数据为例。

我做了一个函数sca.plot。如果参数color.by = null,则制作一个散点图并为所有点染色。如果color.by是某个因素变量,请通过变量制作散点图和颜色点。

我的问题是当我在闪亮的情况下制作互动散点图。如何在SelectInput小部件中包含NULL选项,以便我可以选择这些点是否由某些变量涂色?

如果我在selectInput中选择了null,我会遇到错误。无法弄清楚....

预先感谢。

以下是我的代码:

library(ggplot2)
sca.plot <- function (color.by=NULL) {
    if (is.null(color.by)) {
        diamonds %>% ggplot(aes(x, y))+
            geom_point (color='red')
    } else {
        color.by = sym(color.by)
        diamonds %>% ggplot(aes_(~x, ~y, color=color.by))+
            geom_point ()
    }
}
sca.plot(color.by='clarity')
ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
            selectInput('colorby', label = h5(strong('Color By')),
                        choices = list('clarity', 'cut'),
                        selected = NULL)
        ),
        mainPanel(
            plotOutput('plot') 
            )
        )
    )

server <- function(input, output) {
    output$plot <- renderPlot ({
        sca.plot(color.by=input$colorby)
    })
}
runApp(shinyApp(ui, server))

这是您的解决方案:

library(ggplot2)
library(shiny)
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput('colorby', label = h5(strong('Color By')),
                  choices = list('NULL','clarity', 'cut'),
                  selected = NULL)
    ),
    mainPanel(
      plotOutput('plot') 
    )
  )
)

server <- function(input, output) {
  output$plot <- renderPlot ({
    if(!input$colorby == 'NULL'){
    ggplot(diamonds, aes_string(x="x",y="y", color=input$colorby)) +
        geom_point()
      }else{
      ggplot(diamonds, aes(x=x,y=y)) +
        geom_point(color='red')
    }
  })
}
shinyApp(ui = ui, server = server)

您可以将NULL用作selectInput中的参数,但可以用作字符串 -> 'NULL'

您实际上不需要在Shinny应用程序开头写的那样的功能,您可以在renderPlot()中直接使用if...else...语句来获得geom_point()的所需颜色。

最新更新