Search code examples
rggplot2plotlyggplotly

How to show variables not used for plotting in ggplotly on hover?


Suppose I have 5 variables in a data frame used for plotting using ggplot. I have used 3 out of 5 variables for plotting. When I hover over the scatter plot, I only see 3 variables shown.

Question: How can I show variable 4 along with the other three while hovering?

Sample Example

Using Iris Data set:

p1 <- 
  iris %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point(alpha=0.5) 
ggplotly(p1)

How to get Petal.Length info also displayed while hovering? Image below shows what is currently being shown on hover.

The output currently seen is attached in the image.


Solution

  • ggplotly offers a text "aesthetic" or attribute which could be used to show additional data columns in the tooltip:

    library(plotly)
    
    iris %>%
      ggplot(aes(
        x = Sepal.Length, y = Sepal.Width, color = Species,
        text = paste0("Petal.Length: ", Petal.Length)
      )) +
      geom_point(alpha = 0.5)
    ggplotly()
    

    enter image description here