I have data with groups. For every group I plot a subplot in plotly. The x-values for all of these subplots correspond to identical description, just the y-axis value is either missing or different across groups. I would like to link these subplots so that if I hover over one point in one subplot, it will also highlight the points with the same x value in other subplots. I have tried the crosstalk package examples, but either I create the subplots wrong or I don't understand how to use it. Does anyone have any experience?
Update:
df <- data.frame(
ID = rep(1:4, times = 2),
Value = rnorm(8),
group = c(1,1,1,1,2,2,2,2)
)
subplot(
plot_ly(df[df$group==1,], x = ~ID, y = ~Value),
plot_ly(df[df$group==2,], x = ~ID, y = ~Value), nrows = 2
)
And my question is, how could I highlight the points with the same x value in all subplots if I hover on one of the points?
With the library crosstalk, you first need to transform your dataframe to a SharedData
object to use in several connected plots.
With the function facet_grid()
, you can create separate graphs according to the levels of a variable.
library(plotly)
library(crosstalk)
library(tidyverse)
df <- data.frame(
ID = rep(1:4, times = 2),
Value = rnorm(8),
group = c(1, 1, 1, 1, 2, 2, 2, 2)
)
shared_df <- SharedData$new(df)
ggplotly(
shared_df %>%
ggplot(aes(x = ID, y = Value)) +
geom_point() +
facet_grid(~ group)
)
In the result, if you click on a point on the left graph, it will also highlight this same point on the right graph.