在闪亮的应用程序中的selectinput小部件中包含选项NULL

时间:2017-09-13 05:38:51

标签: r shiny

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

我做了一个函数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))

1 个答案:

答案 0 :(得分:0)

以下是您的解决方案:

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作为参数,但作为字符串 - &gt; 'NULL'

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