23

Is there a way to customize hoverinfo in a ggplotly object?

For example,

p <- ggplot(mtcars, aes(x = disp, y= am, color = as.factor(cyl)))+geom_point()

ggplotly(p)

The hover information box here contains three variables:disp,am and factor(cyl). How to include more variables or exclude existing variables in the hover information box?

Thanks!

3 Answers 3

27

You can include required variables in aes() then use tooltip to specify which should be displayed:

p <- ggplot(mtcars, aes(x = disp, y= am, color = as.factor(cyl), 
                        gear=gear, hp=hp))+geom_point()
ggplotly(p,tooltip = c("x", "gear", "hp"))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That's very helpful.
10

If you want to add html formatting to your hover information you can set the text attribute using paste() in the aes() funtction. Then you use the text value from the aes() in tooltip argument in ggplotly():

p <- ggplot(mtcars, aes(x = disp, y= am, color = as.factor(cyl), 
                        text= paste("Displacment: ", disp, "<br>", 
                                    "Automatic: ", am, "<br>",
                                    "Number of cylinders: ", cyl, "<br>",
                                    "mpg: ", mpg, sep = "")))+
  geom_point()

ggplotly(p, tooltip = c("text"))

This approach allows you to include variables, which are not included in the standard aes() arguments, to the hover info (like mpg in the above code chunk).

Comments

7

A cleaner way is to just add everything within the ggplot environment, using aesthetics two times, in order to pass just the full, single object onto ggplotly():

p <- ggplot(mtcars, aes(label = gear, label2 = hp)) + 
     geom_point(aes(x = disp, y= am, color = as.factor(cyl)))

ggplotly(p)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.