我试图用以下方法对我的箱形图进行子图绘制 plotly
使相同颜色的盒子在x轴上互相对齐。然而,当我用 boxmode = group
:
library(plotly)
library(tidyverse)
df <- data.frame(
w = rep(1:3, times = 2, each = 60),
x = rep(c("A", "B", "C"), times = 20),
y = rep(c("D", "E", "F"), each = 20),
z = rnorm(120)
)
p <- function(val) {
filter(df, w == val) %>%
plot_ly(x = ~x, y = ~z, color = ~y, type = "box") %>%
layout(boxmode = "group")
}
subplot(lapply(unique(df$w), p), nrows = 3, shareX = TRUE)
当使用 ggplot
:
(ggp <- ggplot(df, aes(x = x, y = z, color = y)) +
geom_boxplot() +
facet_wrap(. ~ w, nrow = 3))
但是,如果我试图把这个情节传递给... ggplotly()
:
ggplotly(ggp) %>%
layout(boxmode = "group")
移除 boxmode = "group"
导致不同颜色的盒子互相堆叠,这就更糟糕了!我尝试了一些修改,使用了 "L"。我试过用 alignmentgroup
&amp。offsetgroup
但它们似乎覆盖了 boxmode
参数,并导致一切再次堆叠。我还能做什么来生成一个交互式的图,让每个盒子都保持在它们的车道上?
有类似的问题 此处 但我不认为这能解决我的问题。
被用于 ggplot2
这感觉很笨拙,但它是有效的。诀窍是将单组的boxplots添加为单独的轨迹,并将其设置为 offsetgroup
. 试试这个
library(plotly)
library(tidyverse)
df <- data.frame(
w = rep(1:3, times = 2, each = 60),
x = rep(c("A", "B", "C"), times = 20),
y = rep(c("D", "E", "F"), each = 20),
z = rnorm(120)
)
p <- function(val) {
df <- filter(df, w == val)
# 1. Step by step
# plot_ly(x = ~x, y = ~z, color = ~y) %>%
# #purrr::reduce(unique(df$y), ~ add_trace(.y, data = filter(df, y == .x), type = "box", offsetgroup = .x))
# add_trace(data = filter(df, y == "D"), type = "box", offsetgroup = "D") %>%
# add_trace(data = filter(df, y == "E"), type = "box", offsetgroup = "E") %>%
# add_trace(data = filter(df, y == "F"), type = "box", offsetgroup = "F")
# 2. using purrr::reduce
purrr::reduce(unique(df$y), function(.x, .y) {
add_trace(.x, data = filter(df, y == .y), type = "box",
offsetgroup = .y)
}, .init = plot_ly(x = ~x, y = ~z, color = ~y))
}
subplot(lapply(unique(df$w), p), nrows = 3, shareX = TRUE) %>%
layout(boxmode = "group")
给我这个情节。