2017-09-13 94 views
0

我遇到了我工作中的一些问题。为了解决这个问题,我以钻石数据为例。在闪亮的应用程序中的selectinput小部件中包含选项NULL

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

[This](https://github.com/rstudio/shiny/issues/559)链接应该可以帮到你。 – SBista

+0

@SBista这个链接回答我的问题。谢谢! – zesla

回答

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但作为一个字符串 - >'NULL'

你其实并不需要这样的功能,你在闪亮的应用程序的开头写道,你可以很容易地直接使用if...else...声明在renderPlot()中获取geom_point()的所需颜色。

+0

谢谢。我在实际工作中需要一个功能。 SBista提供的链接解决了我的问题。 – zesla

相关问题