简体   繁体   中英

How to customize hover info while using ggplotly() from plotly package in R?

I am adding a layer of points to a plot made originally in ggplot2 but that I transformed through plotly package into a plotly object. The hover shows info I do not need (points coordinates) and there is a couple o variables that I need to show its values but I can't find the way to do it.

The next example shows my problem. I converted a ggplot2 graph into a plotly one, as is shown below:

library(ggplot2)
library(plotly)
p1 <- ggplot(iris, aes(Sepal.Length, Petal.Width))+
        geom_smooth()
ggplotly(p1)

Then I wanted to add a layer with some points and put certain information in the hover so I could identify which species each point is. I mean I want the Species info to appear in the hover without putting the variable Species in the aesthetics of the ggplot() function.

The closest I've been is this but it does not work either:

ggplotly(p1) %>%
        add_markers(data=iris[1:10,], x=~Sepal.Length, y=~Petal.Width) %>%
        style(hoverlabel="Species")

I want to know if is it possible placing values of other variables in the hover that are not part of the aesthetics set and if can I take off the ones I do not need.

Doing the following will add the species to the existing label:

p1 <- ggplot(iris, aes(Sepal.Length, Petal.Width))+
  geom_smooth()

ggplotly(p1) %>%
  add_markers(data=iris[1:10,], x=~Sepal.Length, y=~Petal.Width) %>% 
  style(hovertext=iris[1:10,"Species"])

There is also a nice answer to a similar question about building the tooltip text into the aesthetic element of the ggplot here . In the bit of testing I did, if you specify the variable in the label in the points aesthetic, then ggplotly(p1) will add that to the existing label. If you instead, call ggplotly(p1, tooltip="label") that will just print the Species: <species> in the tooltip. If instead of label you specify text in the points aesthetic, and call ggplotly(p1, tooltip="text") , you will just get the species name itself in the tooltip.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM