Let me start by 1st mentioning that this sort of linked highlighting can be done client-side (i.e., without shiny) via highlight_key() and highlight(). You can read more about how that works here https://plotly-r.com/client-side-linking.html
p2 <- ggplot(data = highlight_key(data, ~region),
aes(x = week, y = value, group = region)) +
geom_line(colour = 'lightgray') +
facet_wrap(~ country, scales = 'free_y') +
theme_bw()
highlight(ggplotly(p2), color = "red")
You can also embed this result in a shiny app, but for sake of completeness and learning, I'll go through how this could also be done (performantly) in shiny. Note that when you use plotlyProxy() to modify a plotly graph, you need to think on the plotly.js level. In other words, you need to have some understanding how the figure is represented as JSON. plotly_json() is helpful for that:
plotly_json(p)
The most important piece of the figure object is data. Here we have 2 "traces" of data, one for each panel. If you wanted, you could use plotlyProxyInvoke() to "restyle" (that is, modify) those traces, but in this case, it'll be much easier to leverage "addTraces". Moreover, for this example, it makes sense to leverage plotly_build(), which is like plotly_json(), but gives you the figure representation as an R list (instead of JSON). The return object is an htmlwidgets object, but you can get at the underlying plotly.js object in plotly_build(p)$x, and thus, the underlying traces with plotly_build(p)$x$data:
server <- function(input, output, session) {
my_plot <- function(data, colour = 'lightgray') {
ggplot(data, aes(x = week, y = value, group = region, customdata = region)) +
geom_line(colour = colour) +
facet_wrap(~ country, scales = 'free_y') +
theme_bw()
}
output$lineplot <- renderPlotly({
# redraw on double-click it...this _could_ be made more performant with
# plotlyProxyInvoke("deleteTraces", ...), but it'd also be more complicated
event_data("plotly_doubleclick")
my_plot(data)
})
observeEvent(event_data('plotly_click'), {
click <- event_data('plotly_click')
gg <- my_plot(
filter(data, region %in% click$customdata),
colour = "red"
)
plotlyProxy("lineplot", session) %>%
plotlyProxyInvoke("addTraces", plotly_build(gg)$x$data)
})
}