简体   繁体   中英

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?

You need to set the tooltip argument with a vector of variables/aesthetics of the ggplot object (eg 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")

在此处输入图像描述

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")

在此处输入图像描述

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