3

Building up on another question (How to remove duplicate legend entries w/ plotly subplots()), I am facing a new problem. I want all plots in both rows to have the same Y-axis. However, If I turn "shareY = TRUE", the plots on the upper row share an axis, and the plots on the lower row do, but the axis differ from one another.

The code is basically the one from the answer by @Joris Chau, but added "shareY = TRUE" on the last line.

library(plotly)
library(tidyverse)

mpg %>%
  mutate_at("trans", as.factor) %>%  
  group_by(class) %>%
  group_map(.f = ~{          
    ## fill missing levels w/ displ = 0, cyl = first available value 
    complete(.x, trans, fill = list(displ = 0, cyl = head(.x$cyl, 1))) %>%
      plot_ly(x = ~cyl, y = ~displ, color = ~trans, colors = "Paired", type = "bar",
              showlegend = (.y == "2seater"), legendgroup = ~trans) %>%
      layout(yaxis = list(title = as.character(.y)), barmode = "stack")
  }) %>%
  subplot(nrows = 2, shareX = TRUE, shareY = TRUE, titleY = TRUE)   

How can I tell plotly to use the same scale across all plots?

M--
  • 25,431
  • 8
  • 61
  • 93
blabbath
  • 442
  • 7
  • 27
  • I was looking for an answer in python and got to this question, but I found a solution for Python which is: switching the arguments shared_xaxes from True to 'all' does exactly what you are asking for. [Documentation](https://plotly.github.io/plotly.py-docs/plotly.subplots.html). Maybe in R changing the argument shareX from True to "all" could solve it as well. – Gustavo Mar 25 '21 at 20:38

1 Answers1

3

You should define range of yaxis manually. Here, I used c(0,ceiling(max(aggregate(displ ~ cyl+class, mpg, sum)$displ)/10)*10)).

aggregate(displ ~ cyl+class, mpg, sum)$displ gets the summation of displ grouped by cyl + class.

Then I get its maximum and at the end I round it up using ceiling.

library(plotly)
library(tidyverse)

mpg %>%
  mutate_at("trans", as.factor) %>%  
  group_by(class) %>%
  group_map(.f = ~{          
   complete(.x, trans, fill = list(displ = 0, cyl = head(.x$cyl, 1))) %>%
    plot_ly(x = ~cyl, y = ~displ, color = ~trans, colors = "Paired", type = "bar",
            showlegend = (.y == "2seater"), legendgroup = ~trans) %>%
     layout(yaxis = list(title = as.character(.y), 
                         range=c(0, ceiling(max(
                                     aggregate(displ~cyl+class, mpg, sum)$displ)/10)*10)),
            barmode = "stack")
  }) %>%
  subplot(nrows = 2, shareX = TRUE, shareY = FALSE, titleY = TRUE, margin = 0.05)   

M--
  • 25,431
  • 8
  • 61
  • 93