Hover text and formatting in ggplot2 - Plotly
In this article, we are going to explore how to Hover Text and format the plots using R Plotly. The basic idea behind hover text formatting is to make the plot more interactive and informative to the user when one hovers the mouse over it. In R Programming this can be achieved using the Plotly library.
Hover text and formatting using ggplotly
Install and load the required packages
install.packages("ggplot2")
install.packages("plotly")
library(plotly)
library(ggplot2)
Load the default dataset in R(txhousing - Information about the housing market in Texas), Using ggplotly() function we can pass the character vector to the tooltip argument to display the text when one hover over it. The ggplot() function plots the line plot and appends aesthetic mapping to display hover text as follows
data(txhousing)
plot <-ggplot2:: ggplot(txhousing) +
geom_line(aes(date, median, group = city, text = paste0(city, ", TX")))
plotly::ggplotly(plot, tooltip = "text")
Output:

Hover text and formatting using style()
Another way is to use the style() function to modify the default text attribute. After installing and loading the required packages load the default mtcars dataset. Then plot the dot plot of mtcars dataset and hover over the data points.
library(ggplot2)
data(mtcars)
p <- ggplot2::ggplot(mtcars, aes(wt, mpg)) + geom_point()
style(p, text = row.names(mtcars))
Output:
