Reputation: 198
I have 3 subplots created with plot_ly
(one for men, one for women and one for the gap). Since the gap
is the subtraction of m-w
, the ranges of m
and w
are far from the ranges of gap.
Is it possible to share axes only for m
and w
, and keep the axes for gap
free?
shareY=TRUE
and shareX=TRUE
would make all three axes equal, but I only need to share two of them. Also, I don't want to plot the gap in a separate call of plot_ly
because I need the legend to be linked to all the three plots (so I can hide/show markers).
Sample data:
library(dplyr)
library(plotly)
set.seed(197)
a <- tibble(
pais = rep(c("ARGENTINA", "BOLIVIA", "BRASIL", "CHILE", "COLOMBIA"),each = 2),
sexo = rep(c("m", "w"), 5),
ea1 = rnorm(n=10, mean = 50, sd = 1),
ea2 = rnorm(n=10, mean = 40, sd = 1))
a <- a %>%
group_by(pais) %>%
summarise(sexo = "gap",
across(ea1:ea2, ~ -diff(.x))) %>%
bind_rows(a) %>% ungroup()
Plot:
a %>% group_by(sexo) %>%
group_map(~ plot_ly(data=., x = ~ea1, y = ~ea2,
color = ~pais, type = "scatter", mode="markers",
showlegend = (.y == "m"),
legendgroup = ~pais), keep = TRUE) %>%
subplot(nrows = 1, shareX = TRUE, shareY=TRUE)
Upvotes: 1
Views: 508
Reputation: 18714
You don't need to use group_map
for the subplots to share a legend. If you use the same data to create the plots and legend, Plotly is going to gravitate towards keeping a single legend regardless. If you wanted to keep the gaps
free, your best bet is nested subplots. For that, you'll need to pull them out of the group_map
.
First, I'm going to create three separate plots: plt1
, plt2
, and plt3
. Then I'm going to nest their subplots. I'm not entirely sure what you mean about having three plots but wanting the m/f to have a separate space. If they truly share x and y, there is only one plot.
# create a plot for each unique sexo
map(1:length(unique(a$sexo)),
function(h) {
df1 <- filter(a, sexo == unique(a$sexo)[h])
p <- plot_ly(df1, x = ~ea1, y = ~ea2, color = ~pais,
type = "scatter", mode = "markers",
showlegend = (unique(a$sexo)[h] == "m"),
legendgroup = ~pais)
assign(paste0("plt", h), p, envir = .GlobalEnv)
})
Nest them.
subplot(plt1, subplot(plt2, plt3, shareY = T), widths = c(.33, .66))
Upvotes: 2