2017-02-01 8 views
0

私は現在、ggplotを使ってインタラクティブなプロットを作成しています。 マウスをマウスの上に置いたときにハイライト表示されるggplotlyグラフを作成する方法があるかどうかは疑問です。ホバーは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

あなたは光沢で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) 
    }) 
}) 
関連する問題