以另一个问题(How to remove duplicate legend entries w/ plotly subplots())为基础,我面临着一个新问题。我希望两行中的所有图都具有相同的Y轴。但是,如果我将“ shareY = TRUE”设为“ on”,则上一行的图共享一个轴,而下一行的图共享一个轴,但该轴彼此不同。
该代码基本上是@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)
我该如何指示在所有地块上使用相同的比例尺?
答案 0 :(得分:2)
您应该手动定义yaxis
的范围。在这里,我使用了c(0,ceiling(max(aggregate(displ ~ cyl+class, mpg, sum)$displ)/10)*10))
。
aggregate(displ ~ cyl+class, mpg, sum)$displ
获得displ
分组的cyl + class
的总和。
然后我得到最大值,最后我使用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)