繁体   English   中英

悬停使用ggplotly突出显示一行

[英]Hover highlight a line using ggplotly

我目前正在使用ggplot和我正在制作的闪亮应用程序中创建交互式绘图。 我想知道是否有办法创建一个ggplotly图形,当鼠标悬停在它上面时会突出显示一条线。

set.seed(1)
D = data.table(id = rep((1:100),10), value = rnorm(1000), stratification = rep(c("A","B","C","D"), 25))
setkey(D, id)
D = D[, time := 1:10, by = id]

plot = ggplot(data = D, aes(x = time, y = value, group = id, color = stratification) )+
  geom_line()+ 
  theme_classic()  +
  xlab("Time from index (years)") +
  ylab("value") 

ggplotly(plot)

在此图表中是否有一种方法可以在鼠标悬停时突出显示/加粗相应id的行。 这是一个阴谋的选择吗? 如果是这样,有没有办法用ggplotly来实现这个目标?

谢谢。

你可以在有光泽的情况下使用event_data ,但它重绘了服务器上的图,所以它很慢,所以我通过删除一些数据来简化示例:

library(data.table)
library(plotly)
library(shiny)
set.seed(1)
D = data.table(id = rep((1:10),10), value = round(rnorm(100),3), stratification = rep(c("A","B","C","D"), 25))
setkey(D, id)
D = D[, time := 1:10, by = id]

shinyApp(ui=fluidPage(plotlyOutput("myplot")), server=function(input, output, session){
output$myplot = renderPlotly({
  p <- ggplot( )+ 
    theme_classic()  +
    xlab("Time from index (years)") +
    ylab("value") 
  hover_line <- event_data("plotly_hover")
  if(!is.null(hover_line)){
    selected <- D[time==hover_line[[3]] & value==hover_line[[4]],.(id,stratification)]
    print(selected)
    p <- p+ geom_line(data = D[id %in% selected$id & stratification %in% selected$stratification,],aes(x = time, y = value, group = id, color = stratification), size=2)
    p <- p+ geom_line(data = D[!(id %in% selected$id & stratification %in% selected$stratification),],aes(x = time, y = value, group = id, color = stratification))
  } else
    p <- p+ geom_line(data = D,aes(x = time, y = value, group = id, color = stratification))

  ggplotly(p)
  })
})

暂无
暂无

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

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