Plotly scaleY not working across subplot rows

心不动则不痛 提交于 2019-12-23 23:25:06

问题


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?


回答1:


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)   



来源:https://stackoverflow.com/questions/57672160/plotly-scaley-not-working-across-subplot-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!