R ggplot facet_grid多箱图
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了R ggplot facet_grid多箱图相关的知识,希望对你有一定的参考价值。
使用ggplot
和facet_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)可视化一个并行框图。然后对于每个彩色的boxplot,我想有两个boxplot一个用于值,另一个用于value2
我认为除了上面链接的帖子之外,可能还有一个帖子已经解决了。但这是两个问题: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
/ value2
与AAAAAAA
/ 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 additionaly和颜色参数:
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")
以上是关于R ggplot facet_grid多箱图的主要内容,如果未能解决你的问题,请参考以下文章
R:ggplot2:facet_grid:如何在少数(不是全部)标签中包含数学表达式?
R语言ggplot2可视化水平箱图(horizontal boxplot):coord_flip函数将箱图进行旋转
R语言可视化包ggplot2绘制分组箱图实战(Grouped Boxplot)