- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to format mouse over labels using ggplotly in R?
R is a programming language for statistical computing and graphics. ggplotly() is a function that is used to convert a static plot to an interactive web-based version. ggplotly() returns a Plotly object. In this tutorial, we will see how to format mouse over labels using ggplotly in R.
Here, we will use the aes() function that is used for aesthetic mapping between visual cue and a variable. It contains the following arguments: position (X and Y axes), color, fill, shape, line type, and size.
In addition, we will use geom_line() function to set the color and the ggplotly(tooltip="") function to set the tooltip text.
Follow the steps given below to format mouse over labels in Plotly using ggplot in R language.
Step 1
First of all, install the following packages in R.
install.packages('ggplot2') install.packages('plotly') install.packages('readr')
Step 2
Load the following libraries
library(readr) library(ggplot2) library(plotly)
Step 3
Import a CSV file. Create a dataset from the "students_result.csv" file.
students_result <- read_csv("students_result.csv")
Step 4
Create a ggplot using the following arguments
p <- ggplot(data = students_result, aes(x = Year, y = expected, group = 1, text = paste("Year: ", Year, "<br>Expected: ", expected, "<br><b>Final:</b> ", final))) + geom_line(colour = "green", aes(Year, final)) + geom_line(colour = "red")
Step 5
Create tooltip text using the following method
ggplotly(p, tooltip = "text")
Example
Here is the complete code to format mouse over labels in Plotly using ggplotly in R −
library(readr) library(ggplot2) library(plotly) students_result <- read_csv("students_result.csv") p <- ggplot(data = students_result, aes(x = Year, y = expected, group = 1, text = paste("Year: ", Year, "Expected: ", expected, " Final: ", final))) + geom_line(colour = "green", aes(Year, final)) + geom_line(colour = "red") ggplotly(p, tooltip = "text")
Output
It will produce the following output on the browser −
When you get the output on the browser, hover the mouse over the graph to see the formatted tooltip text labels.