Reputation: 11803
I'm running into some issues in my work. To iullustrate the problem, I'm using the diamonds data as an example.
I made a function sca.plot. If the argument color.by=NULL, then make a scatter plot and color all points red. If color.by is some factor variable, make scatter plot and color points by the variable.
My question is when I make interactive scatter plot in shiny. How can I include the NULL option in selectinput widget, so that I can choose whether or not those points are colored by some variable?
If I include NULL in choices in selectinput, I got errors. Could not figure it out....
Thanks a lot in advance.
Below is my code:
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))
Upvotes: 0
Views: 2495
Reputation: 3760
Here is the solution for you:
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)
You can use NULL
as an argument in selectInput
but as a string --> 'NULL'
You actually do not need such a function as you wrote at the beginning of shiny app, you can easily use if...else...
statement directly in renderPlot()
to get the desired color of the geom_point()
.
Upvotes: 1