Hi! I am trying to make an interactive plot such that a single line gets highlighted with colour on click (or hover, but currently this results in million plot reloads). Below is the example of what I am currently doing.
Sample data:
data <- data.frame(country = rep(c('A', 'B'), each = 12*4),
region = rep(c(1, 2, 3, 4), each = 12, times = 2),
week = rep(seq(1, 12, 1), times = 2*4),
value = rnorm(n = 12*4*2))
data <- data %>% mutate(region = paste0(country, region))
ui
ui <- fluidPage(plotlyOutput('lineplot'))
server
server <- function(input, output, session) {
output$lineplot <- renderPlotly({
p <- ggplot(data = data,
aes(x = week,
y = value,
group = region,
customdata = region)) +
geom_line(colour = 'lightgray') +
facet_wrap(~ country, scales = 'free_y') +
theme_bw()
click <- event_data('plotly_click')
if (!is.null(click)) {
selected <- data %>% filter(region == click$customdata)
p <- p + geom_line(data = selected, aes(colour = region))
}
ggplotly(p, tooltip = 'group')
})
}
However, this is a little bit slow since if I understand correctly the whole plot gets rerendered on click. For the same reason hover was resulting in million reloads and therefore was VERY slow.
I came across references to some examples that use observe
and plotlyProxy
(here), but I couldn't get it working with the plot that has facets. Following the example to letter, I only ever managed to add lines to the first panel even though the clicked line belongs to the second panel.
I am new to shiny and ggplotly and plotly, and only just getting the logic of things. But I cannot understand what should I do to I achieve my goal.
Any help is appreciated!
Thanks!