除了这里给出的答案,在refreshColors 的数值条件下,您可以在对eventReactive 的调用中设置ignoreNULL = FALSE,并指定selected = "blue"(或您喜欢的任何颜色)对 radioButtons 的调用。
#this is basically the code from the question with the above changes added
library(shiny)
library(ggplot2)
#data change only once at the begenin
dt <- data.frame(x=runif(100), y=runif(100))
ui <- fluidPage(
sliderInput("point_size","Point Size", value=5, min=1, max=10),
sliderInput("point_alpha","Point Alpha", value=0.8, min=0, max=1),
#here is where you select the default value with selected
radioButtons("point_color","Point Color",choices = c("red","blue","green"),selected = "blue"),
actionButton("refreshColours","Refresh Colors"),
plotOutput("plot_out")
)
server <- function(input,output){
#set igoreNULL = FALSE here
col1 <- eventReactive( input$refreshColours,{input$point_color},ignoreNULL = FALSE)
pp <- reactive({ ggplot(dt, aes(x,y)) +
geom_point(size=input$point_size,
alpha=input$point_alpha, colour=col1()) })
output$plot_out <- renderPlot({ pp() }) }
shinyApp(ui=ui, server=server)
您还可以在对 radioButtons 的调用中使用selected = character(0),这样就不会选择任何单选按钮来启动,并使用一个函数(下面的color_with_default)返回您选择的默认颜色,如果来自radioButtons 为空,因为没有选择时也是如此。该默认颜色用于在应用启动时呈现的初始绘图中,因为在对 eventReactive 的调用中 ignoreNULL 为 false,就像在前面的示例中一样。
library(shiny)
library(ggplot2)
#data change only once at the begenin
dt <- data.frame(x=runif(100), y=runif(100))
ui <- fluidPage(
sliderInput("point_size","Point Size", value=5, min=1, max=10),
sliderInput("point_alpha","Point Alpha", value=0.8, min=0, max=1),
#use selected = character(0) to start with nothing selected
radioButtons("point_color","Point Color",choices = c("red","blue","green"),selected = character(0)),
actionButton("refreshColours","Refresh Colors"),
plotOutput("plot_out")
)
server <- function(input,output){
#here is the function that returns a default grey color if no button is selected
color_with_default <- function( color_in ){
if(is.null(color_in)){
color_in <- "grey"
}
return(color_in)
}
col1 <- eventReactive(eventExpr = input$refreshColours, valueExpr = {input$point_color},ignoreNULL = FALSE)
pp <- reactive({
ggplot(dt, aes(x,y)) +
geom_point(size=input$point_size,
#the call to the color_with_default function is here
alpha=input$point_alpha, colour= color_with_default(col1()))
})
output$plot_out <- renderPlot({ pp() }) }
shinyApp(ui=ui, server=server)