简体   繁体   English

如何在使用 R 中 plotly 包中的 ggplotly() 时自定义悬停信息?

[英]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.我正在向最初在ggplot2制作的绘图添加一层点,但我通过plotly包将其转换为绘图对象。 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:我转换一个ggplot2图表插入到plotly之一,如下所示:

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.我的意思是我希望 Species 信息出现在悬停中,而不会将变量 Species 置于ggplot()函数的美学中。

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 .关于将工具提示文本构建到 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.在我进行的一些测试中,如果您在 points 美学中的label中指定变量,那么ggplotly(p1)会将其添加到现有标签中。 If you instead, call ggplotly(p1, tooltip="label") that will just print the Species: <species> in the tooltip.如果您改为调用ggplotly(p1, tooltip="label") ,它只会在工具提示中打印Species: <species> 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.如果您在点美学中指定text而不是label ,并调用ggplotly(p1, tooltip="text") ,您将只在工具提示中获得物种名称本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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