如何使用 ggplot2 关键特征而不是标签进行选择性标记

How to do selective labeling using ggplot2 key feature instead of label

你好,有没有办法只显示我数据集中特定数据的数据标签?我使用 key 而不是 label 来创建工具提示,但我无法使其工作。作为最终结果,我希望能够像现在一样显示我选择的标签,并且始终显示一些数据标签。

    library(shiny)
    library(plotly)
    library(ggplot2)

    ui <- fluidPage(
      plotlyOutput("iris")
    )

    server <- function(input, output, session) {
      output$iris <- renderPlotly({
          # set up plot
          p1 <- ggplot(iris, aes_string(x = "Sepal.Length", 
                                        y = "Sepal.Width",
                                        key = "Species")) +
              geom_point()+
geom_text(data=subset(iris, Sepal.Lenth > 6),
            aes(Sepal.Length,Sepal.Width,label=Species))

          # get clicked point
          click_data <- event_data("plotly_click", source = "select")
          # if a point has been clicked, add a label to the plot
          if(!is.null(click_data)) {
              label_data <- data.frame(x = click_data[["x"]],
                                       y = click_data[["y"]],
                                       label = click_data[["key"]],
                                       stringsAsFactors = FALSE)
             p1 <- p1 + 
                 geom_text(data = label_data,
                           aes(x = x, y = y, label = label),
                           inherit.aes = FALSE, nudge_x = 0.25)
          }
          # return the plot
          ggplotly(p1, source = "select", tooltip = c("key"))
      })
      }

    shinyApp(ui, server)

一个可能的解决方案是:

library(shiny)
library(plotly)
library(ggplot2)

p1 <- ggplot(iris, aes_string(x = "Sepal.Length", 
                              y = "Sepal.Width",
                           text = "Species")) +
      geom_point() +
      geom_text(data=subset(iris, Sepal.Length > 6),
        aes(Sepal.Length,Sepal.Width,label=Species))

ui <- fluidPage(
        plotlyOutput("iris")
      )

server <- function(input, output, session) {   
           output$iris <- renderPlotly({
           # get clicked point
           click_data <- event_data("plotly_click", source = "select")
           # if a point has been clicked, add a label to the plot
           if(!is.null(click_data)) {
              pos <- click_data$pointNumber+1
              label_data <- data.frame(x = iris$Sepal.Length[pos],
                                       y = iris$Sepal.Width[pos],
                                       label = iris$Species[pos],
                                       stringsAsFactors = FALSE)
              p1 <<- p1 + 
                 geom_text(data = label_data,
                           aes(x = x, y = y, label = label),
                           inherit.aes = FALSE, nudge_y=.1)
          }
          # return the plot
          ggplotly(p1, source = "select", tooltip = c("text"))
      })
      }

shinyApp(ui, server)