How can one code the following click event in plotly (and/or dash)? Let us assume that we have two plots (e.g. a subplot or anything else that works). When a user clicks inside the top plot (either on a dot or on any space in-between), the x-value of the click-event (x-click) should be registered and used to update the x-axis range of the window in the bottom plot (i.e. display the range from x-click - 50 to x-click + 50).
To make this more clear, here is some sample code generating a time series (display a window of it in a bottom plot) and the distances of its local maxima (display it as the top plot where a click defines the window of the bottom plot):
library(plotly) library(ggplot2) # generate some random and relatively smooth time series set.seed(114) M <- 1000 r <- rnorm(M) y <- cumsum(r) x <- 1:length(y) y <- loess(y~x, span = 0.15)$fitted # cacluate the local maxima of time series peaks <- ggpmisc:::find_peaks(y) xpeaks <- x[peaks] # plot 1: distances between local maxima of the time series y1 <- xpeaks[2:length(xpeaks)]-xpeaks[1:(length(xpeaks)-1)] # distance between successive peaks x1 <- (xpeaks[2:length(xpeaks)]+xpeaks[1:(length(xpeaks)-1)])/2 # midpoint of successive peaks data1 <- data.frame(y=y1,x=x1) g1 <- ggplot(data1, aes(y=y, x = x)) + geom_point() p1 <- ggplotly(g1) # plot 2: window of the timeseries x2 <- xpeaks # here it is just some value, but x2 should become the clicked x-value in plot 1 timewindow <- (x2-50):(x2+50) # select +-50 points around x2 to display data2 <- data.frame(y=y[timewindow], x = x[timewindow]) g2 <- ggplot(data2, aes(x= x, y = y)) + geom_line() p2 <- ggplotly(g2) subplot(p1, p2, nrows = 2, heights = c(0.8,0.2))
Visually, this is what I wish to achieve:
Your kind help is greatly appreciated!