Reputation: 7858
Look at the following reproducible example:
# libraries
library(ggplot2)
library(plotly)
# data
set.seed(1)
df <- data.frame(x = rnorm(100), y = rnorm(100))
# ggplots
g1 <- g2 <- ggplotly(ggplot(df, aes(x, y)) + geom_point())
# set together
subplot(g1, g2, shareX = TRUE, shareY = TRUE)
This is the result:
When I zoom over the Y axis in one of the two plots the other one will update consequently, however if I zoom over the X axis only the plot I'm working on will change.
When I do this:
I get this:
Notice that the X axis on the right didn't change.
shareX = TRUE
doesn't do the trick.
How can I solve?
Upvotes: 3
Views: 273
Reputation: 41601
You could use matches
with layout
to each ggplotly
to change the x axis automatically on both graphs like this:
# libraries
library(ggplot2)
library(plotly)
# data
set.seed(1)
df <- data.frame(x = rnorm(100), y = rnorm(100))
# ggplots
g1 <- g2 <- ggplotly(ggplot(df, aes(x, y)) + geom_point()) %>%
layout(xaxis = list(matches = "x"))
# set together
subplot(g1, g2, shareX = TRUE, shareY = TRUE)
Created on 2023-02-10 with reprex v2.0.2
Here an example:
Upvotes: 1
Reputation: 2140
You can use plot_ly() function rather than ggplotly() for making the plots. This is because in addition to creating static plots, plots are interactive, allowing you to zoom, hover, and interact with the data in various ways.
library(plotly)
set.seed(1)
df <- data.frame(x = rnorm(100), y = rnorm(100))
g1 <- plot_ly(df, x = ~x, y = ~y, type = "scatter", mode = "markers")
g2 <- plot_ly(df, x = ~x, y = ~y, type = "scatter", mode = "markers")
subplot(g1, g2, nrows = 1, shareX = TRUE, shareY = TRUE)
The code ensures that the X and Y axes are synchronized between the two plots. Hope it could helps!
output plot
Zoomed plots between x(0-2) and y(0-0.5) as example:
Upvotes: 1