2017-02-01 1 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) 
    }) 
}) 
관련 문제