plotly.R
plotly.R copied to clipboard
Zoom all facets at the same time
There seems to be a discrepancy between plotly for R and for python in how it handles zooming across facets.
To take my examples directly from the documentation: https://plotly.com/ggplot2/facet-plots/ vs https://plotly.com/python/facet-plots/
In the python version, if I select a region to zoom in on, the same zoom is applied to all facets, regardless of position.
In the r version, if I zoom on one facet, the 'x' zoom is applied to facets in the same column, and the 'y' zoom is applied to facets in the same row - but other facets are unaffected.
I would like to replicate the python behaviour in r. Any clues for how to do this?
Reprex: Compare zoom behaviour between R and python
library(reshape2)
library(plotly)
p <- ggplot(tips, aes(x=total_bill)) + geom_histogram(binwidth=2,colour="white")
# Histogram of total_bill, divided by sex and smoker
p <- p + facet_grid(sex ~ smoker)
ggplotly(p)
import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df, x='gdpPercap', y='lifeExp', color='continent', size='pop',
facet_col='year', facet_col_wrap=4)
fig.show()
For anyone who comes across this in the future, I was able to manually achieve this via the Layout Axis Matches setting. Here is the updated R Reprex that I believe achieves the original ask.
library(reshape2)
library(plotly)
p <- ggplot(tips, aes(x=total_bill)) + geom_histogram(binwidth=2,colour="white")
# Histogram of total_bill, divided by sex and smoker
p <- p + facet_grid(sex ~ smoker)
ggplotly(p) %>%
layout(
xaxis = list(matches = 'x2'),
yaxis = list(matches = 'y2')
)
Note that if you have more than 2X2, then you will need to set additional match settings as shown in this 3X3 example.
library(dplyr)
tips2 <- tips %>%
mutate(sex = ifelse(sample(0:1, n(), replace = TRUE) == 1, '3', sex),
smoker = ifelse(sample(0:1, n(), replace = TRUE) == 1, '3', smoker))
p2 <- ggplot(tips2, aes(x=total_bill)) + geom_histogram(binwidth=2,colour="white")
# Histogram of total_bill, divided by sex and smoker
p2 <- p2 + facet_grid(sex ~ smoker)
ggplotly(p2) %>%
layout(
xaxis = list(matches = 'x2'),
yaxis = list(matches = 'y2'),
xaxis2 = list(matches = 'x3'),
yaxis2 = list(matches = 'y3')
)