繁体   English   中英

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

这是我目前的情节。

在此处输入图片说明

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

我认为除了我上面链接的那篇文章外,可能还有一篇已经解决过的文章。 但这是两件事的问题:1)将数据转换为ggplot期望的格式,即长形的,因此有值可以映射到美学上; 2)关注点分离,因为您可以使用reshape2或(更多-to-date) 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 / value2AAAAAAA / BBBBBBB 您可能需要相应地交换aes分配。

您必须重塑数据框架。 使用附加的指示符(列)来定义值的类型(例如“ 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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM