我目前正在使用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来实现这个目标?
谢谢。
答案 0 :(得分:0)
你可以在闪亮的情况下使用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)
})
})