Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly scaleY not working across subplot rows

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?

like image 601
blabbath Avatar asked Dec 07 '25 20:12

blabbath


1 Answers

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)   

like image 54
M-- Avatar answered Dec 09 '25 13:12

M--