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

问题描述

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

当我使用 ggplotly 时,会显示构面,但只显示第一个构面的数据。 facet_grid 也是如此。 (我更喜欢使用 facet_wrap 以便我可以在不同方面之间使用自由尺度。)

有没有办法让 ggplotly 以这种方式处理构面?我在 ggplotly documentation 中没有看到任何东西。我见过其他例子,其中人们有 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

enter image description here

# ggplotly object only shows first facet
ggplotly(pwrap)

enter image description here

# 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')

会话信息: 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)。 附带说明一下,您可以通过在 scales='free' 命令中使用 facet_wrap(facets = 'A',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' 并且不使用宽度选项,两个图的不同之处在于第二个图居中(图未附加),请让我知道它是否有帮助:

# 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)

第一个版本的输出

enter image description here

,

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)

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...