Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

r - How to choose a variable to display via the tooltip of ggplotly

I am trying to do something similar to this How to choose variable to display in tooltip when using ggplotly?

But the difference is I have two time series and the solution suggested in that link doesn't work. So this is what I tried:

library(ggplot2)
library(plotly)
library(dplyr)


t = rnorm(10, 0, 1)
x = rnorm(10, 0, 1)
y = rnorm(10, 0, 1)
z = rnorm(10, 0, 1)

df = data.frame(t,x,y,z)

p = df %>% ggplot() + geom_point(aes(t, x, text = paste(z)), color = "red") +
                  geom_point(aes(t, y), color = "blue")

ggplotly(p , tooltip = "z")

I want to show the value of z when I hover on the points. Any idea how to do that here?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to set the tooltip argument with a vector of variables/aesthetics of the ggplot object (e.g. x, y, size, fill, colour...), not columns from your original dataframe (which is what you did).

You are mapping the values of z to text in geom_point (which does not exist in ggplot, so you should be getting a warning). So just set tooltip = "text" (note that the blue points will have no tooltips in this case, because you did not set the text aesthetic there)

p = df %>% ggplot() + geom_point(aes(t, x, text = paste(z)), color = "red") +
  geom_point(aes(t, y), color = "blue")

ggplotly(p , tooltip = "text")

enter image description here

From the help page of ggplotly (you can read this by typing ? ggplotly in the R console)

tooltip

a character vector specifying which aesthetic mappings to show in the tooltip. The default, "all", means show all the aesthetic mappings (including the unofficial "text" aesthetic). The order of variables here will also control the order they appear. For example, use tooltip = c("y", "x", "colour") if you want y first, x second, and colour last.


EDIT: with geom_line

When you use the unofficial text aesthetic in geom_line it messes up with the grouping of the points (see discussion in the link at the beginning of the question). One fix for this is to explicitly tell geom_line to group all points together by adding the group=1 parameter.

p = df %>% ggplot() + geom_line(aes(t, x, text = paste(z), group=1), color = "red") +
  geom_line(aes(t, y), color = "blue")

ggplotly(p , tooltip = "text")

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...