修改Shiny环境下鸢尾花K-means Plotly图的悬停显示文本
Got it, let's fix that hover text issue! The problem here is that when you use iris[,1] and iris[,2] in your aes() call, ggplot doesn't recognize the actual variable names—it just sees generic indexed column references, so Plotly uses those unhelpful labels in the hover tooltip. We can adjust this to directly use the selected variable names, so hover shows meaningful labels like Sepal.Length instead of iris[,1].
Here's the revised code with key fixes explained:
library(plotly) library(shiny) library(ggplot2) vars <- setdiff(names(iris), "Species") ui <- pageWithSidebar( headerPanel('Iris k-means clustering'), sidebarPanel( selectInput('xcol', 'X Variable', vars), selectInput('ycol', 'Y Variable', vars, selected = vars[[2]]), numericInput('clusters', 'Cluster count', 3, min = 1, max = 9) ), mainPanel( plotlyOutput('plot1') ) ) server <- function(input, output, session) { output$plot1 <- renderPlotly({ # Create a subset with only selected variables (avoid overwriting original dataset) selected_iris <- iris[, c(input$xcol, input$ycol)] cls <- kmeans(x = selected_iris, centers = input$clusters) selected_iris$cluster <- as.character(cls$cluster) # Build ggplot with proper variable references for hover text p <- ggplot(selected_iris) + geom_point(aes(x = .data[[input$xcol]], y = .data[[input$ycol]], colour = cluster)) + # Use continuous scales since iris features are numeric (fixes axis formatting) scale_x_continuous(name = input$xcol) + scale_y_continuous(name = input$ycol) + theme_light() + geom_text( aes(x = cls$centers[, input$xcol], y = cls$centers[, input$ycol], label = 1:input$clusters), color = "black", size = 4 ) ggplotly(p) }) } shinyApp(ui, server)
Key Changes Made:
- Replaced
iris[,1]/iris[,2]with.data[[input$xcol]]/.data[[input$ycol]]: The.datapronoun tells ggplot to use the actual variable names from your dropdown selections. This makes Plotly display those meaningful names in the hover tooltip instead of generic indexed labels. - Renamed the subset to
selected_iris: Avoids overwriting the originalirisdataset—good practice to prevent unintended side effects in more complex apps. - Swapped discrete scales for continuous scales: Iris features are numeric values, so
scale_x_discrete/scale_y_discretewere causing wonky axis formatting. Using continuous scales fixes this and ensures proper data scaling. - Cleaned up code structure: Assigning the ggplot to a variable
pbefore converting to plotly makes the code more readable and easier to debug.
Now when you hover over data points, the tooltip will display the selected variable names (e.g., Sepal.Length, Petal.Width) along with their values and cluster assignment—exactly what you wanted!
内容的提问来源于stack exchange,提问作者firmo23

