Plotly: Hoverinfo for both points connected by line (“markers+lines”) using group_by

时光总嘲笑我的痴心妄想 提交于 2019-12-12 10:23:23

问题


I am making a line chart and I would like to have hoverinfo for both points connected by line. I know that ggplotly() uses tooltip for this. I think I should use hovermode in plot_ly() layout. The highlight in my follwoing example does exactly what I want: highlight both marks and the line connecting them. I would like to have hoverinfo for both marks when I hover either of them (and if possible the line connecting them), i.e. hoverinfo by variable used in group_by().

This SO post is does something similar to what I want but it uses ggplotly() while I would like to do it with plot_ly(), and I would like to have hoverinfo showing for both grouped marks when hovering any of them.

## Simulate some Data
set.seed(81)   
df <- data.frame(id = rep(1:100, 2),
                 x = c(rep("Pre", 100), rep("Post", 100)), 
                 y = round(runif(200), 2), 
                 z = round(rnorm(200, mean = 50, sd = 10)),
                 q = round(rnorm(200, mean = 70, sd = 20)))
df <- df[-sample(1:nrow(df), size = 20) , ]                               # delete some rows at random to simulate missing values


df$x <- factor(df$x, levels = c("Pre", "Post"))          # relevel Pre Post for plot
df$x_jitter <- jitter(as.numeric(df$x))             # add jitter to x discrete var before piping to plotly

#####################################

## Plot
library(plotly)
library(tidyverse)


df_high <- highlight_key(df, ~id )

p1 <- plot_ly()
p1 <- 
  p1 %>% 
  add_data(df_high) %>%
  group_by(id) %>%    
  add_trace(x = ~x_jitter, y = ~y,                                             
            type = 'scatter', mode = 'markers+lines',
            color = I("black"), alpha = 0.9,
            hoverinfo = 'text+y', text = ~paste("ID: ", id, "<br>"),       
            showlegend = FALSE
  )  %>%

  layout(hovermode = "group") %>%  # THIS IS WEHERE I NEED HELP

  highlight(on = 'plotly_select', off = 'plotly_deselect', 
            selected = attrs_selected(mode = "markers+lines", marker = list(symbol = "x")))

p1

Created on 2019-08-26 by the reprex package (v0.3.0)

来源:https://stackoverflow.com/questions/57655036/plotly-hoverinfo-for-both-points-connected-by-line-markerslines-using-grou

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!