You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改Shiny环境下鸢尾花K-means Plotly图的悬停显示文本

Fixing Hover Text in Iris K-means Plotly Shiny App

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 .data pronoun 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 original iris dataset—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_discrete were causing wonky axis formatting. Using continuous scales fixes this and ensures proper data scaling.
  • Cleaned up code structure: Assigning the ggplot to a variable p before 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 09:43:11