基于Shiny与DT库实现selectInput自定义绘图选中点颜色的求助
Hey there! I see exactly where you went wrong—let's get this working smoothly for you.
The Root Cause
When you set col = "input$color", you're passing a literal string "input$color" to the points() function, not the actual value of the user's color selection from the selectInput. R doesn't recognize this as a valid color name, which is why you got that error.
Step-by-Step Fix
Place the
selectInputlogically in your UI
Let's add it right above the plot in thecolumn(4)section so it's grouped with the element it controls:column(4, h3("p5"), selectInput("color", "What is your preferred color?", choices = c("blue", "gold", "green", "pink", "red", "yellow")), plotOutput("p5") )Update the
points()call in your server
Remove the quotes aroundinput$color—this lets Shiny access the reactive value of the user's selected color instead of treating it as plain text:points(iris[s, c("Sepal.Length", "Sepal.Width"), drop = F], pch = 19, cex = 1, col = input$color) # No quotes here!
Full Modified Code
Here's the complete working code with changes highlighted:
library(shiny) library(DT) ui <- fluidPage( h3("t1"), tableOutput("t1"), hr(), fluidRow( column(9, h3("dt1"), dataTableOutput("dt1")), column(3, h3("x4"), verbatimTextOutput("x4")) ), hr(), fluidRow( column(8, h3("dt2"), dataTableOutput("dt2")), column(4, h3("p5"), # Added selectInput here for better UI flow selectInput("color", "What is your preferred color?", choices = c("blue", "gold", "green", "pink", "red", "yellow")), plotOutput("p5") ) ) ) options(error = function() traceback(2)) server <- function(input, output, session) { output$t1 <- renderTable(iris[1:10,], striped = TRUE, hover = TRUE) output$dt1 <- renderDataTable(iris, options = list( pageLength = 5)) output$x4 <- renderPrint({ s = input$dt1_rows_selected if (length(s)) { cat('These rows were selected:\n\n') cat(s, sep = ', ') } }) output$dt2 <- renderDataTable(iris, options = list(pageLength = 5), server = FALSE) output$p5 <- renderPlot({ s <- input$dt2_rows_selected plot(iris$Sepal.Length, iris$Sepal.Width) if (length(s)) { # Removed quotes around input$color to use the reactive value points(iris[s, c("Sepal.Length", "Sepal.Width"), drop = F], pch = 19, cex = 1, col = input$color) } }) } shinyApp(ui, server)
How It Works Now
- The
selectInputcreates a reactive variableinput$colorthat updates automatically when the user picks a new color. - By using
col = input$color(without quotes), Shiny fetches the current value of this input and passes it topoints(), so the selected scatter points will always match the user's chosen color.
内容的提问来源于stack exchange,提问作者Chen JG Thomas

