Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Legends of multiple ggplots with facet_grids are not displayed correctly with subplot #1757

Closed
MarcoPortmann opened this issue Apr 30, 2020 · 1 comment

Comments

@MarcoPortmann
Copy link

I want to plot several ggplots with facet_grids with plotly. The plots should have a common legend. Unfortunately, I can't get it that the y-axes are not cut off (#1224), only one legend is displayed and there are no repetitions in the legend, as in the example:

library(plotly)

mtcars2 <- mtcars
mtcars2$gear <- factor(mtcars$gear)
mtcars2$vs <- factor(mtcars$vs)

pl1 <- ggplot(mtcars2, aes(x = cyl, y = disp, color = gear)) +
  geom_point() + facet_grid(cols = vars(vs)) + ylab("display")

pl2 <- ggplot(mtcars2, aes(x = qsec, y = disp, color = gear)) +
  geom_point() + facet_grid(cols = vars(vs)) + ylab("q sec")

subplot(pl1, pl2, margin = 0.10)

image

I have found the same question several times on stackoverflow, but unfortunately without a working solution.

Among other things it is suggested to create a ggplot with several facets instead of several ggplots. However, I create a shiny app where the user can customize the plots and maybe has already defined facet rows and columns. Also the plots have different y-axis labels because the units are different (It is not impossible to define different ylabs for each facet, but actually it does not correspond to the ggplot philosophy and needs some tweaking).

I would be grateful for a solution or a workaround to this problem.

@cpsievert
Copy link
Collaborator

This is a big hack, but I think it does what you want

p <- subplot(hide_legend(pl1), pl2, margin = 0.03) %>%
  plotly_build()

grps <- vapply(p$x$data, function(trace) trace$legendgroup, character(1))
p$x$data <- Map(function(trace, show) { 
  trace$showlegend <- show
  trace
  }, p$x$data, !duplicated(grps))
p

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants