【问题标题】:Plotly scaleY not working across subplot rowsPlotly scaleY 不适用于子图行
【发布时间】:2019-12-31 11:40:24
【问题描述】:

基于另一个问题 (How to remove duplicate legend entries w/ plotly subplots()),我面临一个新问题。我希望两行中的所有图都具有相同的 Y 轴。但是,如果我打开“shareY = TRUE”,上排的图共享一个轴,下排的图共享一个轴,但轴彼此不同。

代码基本上来自@Joris Chau 的答案,但在最后一行添加了“shareY = TRUE”。

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)   

我怎样才能告诉情节在所有情节中使用相同的比例?

【问题讨论】:

  • 我在 python 中寻找答案并解决了这个问题,但我找到了 Python 的解决方案:将参数 shared_xaxes 从 True 切换为 'all' 正是您所要求的。 Documentation。也许在 R 中将参数 shareX 从 True 更改为“all”也可以解决它。

标签: r plotly tidyverse r-plotly


【解决方案1】:

您应该手动定义yaxis 的范围。在这里,我使用了c(0,ceiling(max(aggregate(displ ~ cyl+class, mpg, sum)$displ)/10)*10))

aggregate(displ ~ cyl+class, mpg, sum)$displ 获取由cyl + class 分组的displ 的总和。

然后我得到它的最大值,最后我使用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)   

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 2021-07-23
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 2012-06-15
    • 2016-04-02
    相关资源
    最近更新 更多