Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create a tooltip using code in ggplot and tidyverse, you need to use the ggplotly function from the plotly package. The following steps outline the process:

  1. Load the required libraries:
library(ggplot2)
library(plotly)
  1. Create the ggplot object and specify the aesthetic mappings:
p <- ggplot(data = mtcars, aes(x = mpg, y = wt)) +
  geom_point()
  1. Convert the ggplot object to a plotly object using the ggplotly function:
p <- ggplotly(p)
  1. Specify the tooltip information using the tooltip function:
p <- p %>% 
  layout(
    hoverlabel = list(
      namelength = -1
    ),
    tooltip = list(
      formatter = "function(variable, value) {
        if(variable === 'mpg') {
          return('Miles per gallon: ' + value);
        } else {
          return('Weight: ' + value);
        }
      }"
    )
  )
  1. Customize the tooltip formatting by specifying the variables and formatting instructions inside the formatter function.

  2. Display the plot:

p

The resulting plot will have a tooltip pop-up when you hover over each point, displaying the values of the mpg and wt variables.