使用ggplotly with facet_wrap时,只出现第一个facet的数据

When using ggplotly with facet_wrap, only the data of the first facet appears

我正在使用 ggplot() + geom_boxplot() + facet_wrap() 为多个组绘制箱线图。我想在此 object 上使用 ggplotly() 来使用悬停工具提示,以便我可以快速查看与异常值相关的数据。 (为什么我不只是在图上注释?我将向工具提示添加自定义文本,它比我希望出现在图上的固定注释中的文本更广泛。)

当我使用ggplotly时,虽然显示了facet,但只显示了第一个facet的数据。 facet_grid也是如此。 (我更愿意使用 facet_wrap 这样我就可以在不同的面之间使用自由尺度。)

有没有办法让 ggplotly 以这种方式处理分面?我在 ggplotly documentation. I've seen other examples where people have other issues with their facets 中没有看到任何内容,但所有方面都在那里。

# make data: 
# B: normal distribution divided across 3 groups
# C: group Z is on a different scale
df <- data.frame(A = rep(LETTERS[seq( from = 24, to = 26 )], 26*5),
                 B = rnorm(26*15))
df <- df %>% mutate(C = ifelse(A == 'Z', B*7, 
                               ifelse(A == 'Y', B + 7, B)))

# plot using facet_wrap
pwrap <- ggplot(df, aes(y = C)) +
  geom_boxplot() +
  theme_classic() +
  facet_wrap(facets = 'A')
# ggplot object shows fine
pwrap

# ggplotly object only shows first facet
ggplotly(pwrap)

# plot using facet_grid
pgrid <- ggplot(df, aes(y = C)) +
  geom_boxplot() +
  theme_classic() +
  facet_grid(.~A)
# again, ggplot object shows fine
pgrid
# but ggplotly object is limited to first facet
ggplotly(pgrid)

# my goal: facet_wrap to allow 'free' y-scales for variable C, with ggplotly hover info
ggplot(df, aes(y = C)) +
  geom_boxplot() +
  theme_classic() +
  facet_wrap(~A, scales = 'free')

Session 信息: R 版本 4.0.3 (2020-10-10) 平台:x86_64-w64-mingw32/x64(64 位) 运行 下:Windows 10 x64(内部版本 19041) ggExtra_0.9
plotly_4.9.3 ggplot2_3.3.3

它真的来了,但你看不到它,如果你 zoom out 找到所有的图,你可以像下面那样修改你的代码以使其工作,这里我将宽度更改为意味着列 mean(df$C)。 附带说明一下,您可以通过在 facet_wrap(facets = 'A', scales='free') 命令中使用 scales='free' 来改善它,但在这种情况下,您有三个垂直轴。

pwrap <- ggplot(df, aes(y = C)) +
  geom_boxplot(width=mean(abs(df$C))) +
  theme_classic() +
  facet_wrap(facets = 'A')
# ggplot object shows fine
pwrap
ggplotly(pwrap)

另一个版本(缩放版本),使用 x = 1 和 scales='free' 并且不使用 width 选项,两个图的区别在于第二个图居中(图未附上) ,如果有帮助,请告诉我:

# plot using facet_wrap
pwrap <- ggplot(df, aes(x = 'X', y = C)) +
  geom_boxplot() +
  theme_classic() +
  facet_wrap(~A, scales='free') 
# ggplot object shows fine
pwrap
ggplotly(pwrap)

第一个版本的输出:

PKumar 的解决方案很接近(定义 x 变量),但 x 轴的行为仍然不如我预期。解决方案是确保 x 变量是一个因子。

# plot using facet_wrap
pwrap <- ggplot(df, aes(x = as.factor(A), y = C)) + # x is a factor (as.factor('X') also OK if trying to match PKumar's answer)
  geom_boxplot() +
  theme_classic() +
  facet_wrap(~A, scales='free') 

# ggplot object
pwrap

# now a functional 
ggplotly(pwrap)