R ggplot facet_grid 多箱线图

R ggplot facet_grid multi boxplot

使用 ggplotfacet_grid,我想通过箱形图可视化两个平行的值向量。我的可用数据:

DF <- data.frame("value" =  runif(50, 0, 1),
             "value2" = runif(50,0,1),
             "type1" = c(rep("AAAAAAAAAAAAAAAAAAAAAA", 25), 
                         rep("BBBBBBBBBBBBBBBBB", 25)),
             "type2" = rep(c("c", "d"), 25), 
             "number" = rep(2:6, 10))

目前的代码只允许可视化一个值向量:

ggplot(DF, aes(y=value, x=type1)) + 
  geom_boxplot(alpha=.3, aes(fill = type1)) + 
  ggtitle("TITLE") + 
  facet_grid(type2 ~ number) +
  scale_x_discrete(name = NULL, breaks = NULL) + # these lines are optional
  theme(legend.position = "bottom")

这是我现在的剧情。

我想为每个向量(数据框中的值和值 2)可视化一个平行箱线图。然后对于每个彩色箱线图,我想要两个箱线图,一个用于 value,另一个用于 value2

您必须重塑数据框。使用另外一个指标(列)来定义值的类型(例如 "value_type"),并且只定义一个值列。然后,指标会将值与相应的值类型相匹配。以下代码将重塑您的示例:

DF <- data.frame("value" =  c(runif(50, 0, 1), runif(50,0,1)),
                 "value_type" = rep(c("value1","value2"), each=50),
                 "type1" = rep(c(rep("AAAAAAAAAAAAAAAAAAAAAA", 25), 
                                 rep("BBBBBBBBBBBBBBBBB", 25)), 2),
                 "type2" = rep(rep(c("c", "d"), 25), 2), 
                 "number" = rep(rep(2:6, 10),2))

另外使用带有颜色参数的 ggplot:

ggplot(DF, aes(y=value, x=type1, col=value_type)) + 
  geom_boxplot(alpha=.3, aes(fill = type1)) + 
  ggtitle("TITLE") + 
  facet_grid(type2 ~ number) +
  scale_color_manual(values=c("green", "steelblue")) + # set the color of the values manualy
  scale_x_discrete(name = NULL, breaks = NULL) +# these lines are optional
  theme(legend.position = "bottom")

我认为除了我在上面链接的那个之外,可能还有一个 post 已经解决了这个问题。但这是两个问题:1) 将数据转换为 ggplot 期望的格式,即长形,以便将值映射到美学上,以及 2) 关注点分离,因为您可以使用 reshape2 或(最新的)tidyr 函数将数据转换为正确的形状,ggplot2 函数绘制它。

您可以使用 tidyr::gather 获取长数据,并方便地将其直接传输到 ggplot

library(tidyverse)
...

为了说明,尽管使用非常通用的列名:

DF %>%
  gather(key, value = val, value, value2) %>%
  head()
#>                    type1 type2 number   key       val
#> 1 AAAAAAAAAAAAAAAAAAAAAA     c      2 value 0.5075600
#> 2 AAAAAAAAAAAAAAAAAAAAAA     d      3 value 0.6472347
#> 3 AAAAAAAAAAAAAAAAAAAAAA     c      4 value 0.7543778
#> 4 AAAAAAAAAAAAAAAAAAAAAA     d      5 value 0.7215786
#> 5 AAAAAAAAAAAAAAAAAAAAAA     c      6 value 0.1529630
#> 6 AAAAAAAAAAAAAAAAAAAAAA     d      2 value 0.8779413

将其直接输入 ggplot:

DF %>%
  gather(key, value = val, value, value2) %>%
  ggplot(aes(x = key, y = val, fill = type1)) +
    geom_boxplot() +
    facet_grid(type2 ~ number) +
    theme(legend.position = "bottom")

同样,由于一些通用的列名,我不能完全确定这是你想要的设置——就像我不知道 value / value2value2 的区别一样AAAAAAA / BBBBBBB。您可能需要相应地交换 aes 作业。