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

Hello is there a way to display the data labels only for specific data of my dataset? I used key instead of ``label` in order to create the tooltip but I cannot make it work. As a final result I want to be able to display labels of my choice as now and also have some data labels always displayed.

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 > 10),
            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)

Here's a recent tweet which might help:

3 Likes