Open In App

Hover text and formatting in ggplot2 – Plotly

Last Updated : 05 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

R




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

R




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 in ggplot2 - Plotly

 

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.

R




library(ggplot2)
  
data(mtcars)
  
p <- ggplot2::ggplot(mtcars, aes(wt, mpg)) + geom_point()
style(p, text = row.names(mtcars))


Output:

Hover text and formatting in ggplot2 - Plotly

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads