2017-09-13 93 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

相關問題