Edo
Edo

Reputation: 7858

Can I zoom in a plot and have the other plot to zoom in the same way? (ggplot and plotly)

Reproducible

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:

enter image description here

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.

Problem

When I do this:

enter image description here

I get this:

enter image description here

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

Answers (2)

Quinten
Quinten

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:

enter image description here

Upvotes: 1

SAL
SAL

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

enter image description here

Zoomed plots between x(0-2) and y(0-0.5) as example: enter image description here

Upvotes: 1

Related Questions