如何在R中制作多对箱形图?

时间:2016-09-30 02:34:33

标签: r boxplot

我有一个包含近4,000个观测值的数据集,其中包含9个不同的组。所以我有以下变量

群组: 1,2,3,....,9

性别:男,女

体重:每个人的体重

我想要做的是为每组制作一对箱形图(男性,女性)。所以在这种情况下我将有18个箱图。

如果不为每个boxplot(subset()which())函数创建一个子集数据,我该怎么做呢。

除此之外我对这些数据有一些问题,有一些没有重量的观察,细胞是空的或.点。

这是一个虚构的样本,有3组,其中性别= 1表示女性,2表示男性。

Group     Sex   Weight
1         1     140
1         2
1         2     160
1         1     154
1         1     127
2         2     182
2         2     192
2         1     .
2         1     147
2         1     129
3         1     124
3         2     182
3         1     .
3         2     141
3         1     148

我从未使用过这个dput()函数,我不知道它是否正确

dput(data)
structure(list(Group = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 
2L, 3L, 3L, 3L, 3L, 3L), Sex = c(1L, 2L, 2L, 1L, 1L, 2L, 2L, 
1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L), Weight = structure(c(6L, 1L, 
11L, 10L, 4L, 12L, 13L, 2L, 8L, 5L, 3L, 12L, 2L, 7L, 9L), .Label = c("", 
".", "124", "127", "129", "140", "141", "147", "148", "154", 
"160", "182", "192"), class = "factor")), .Names = c("Group", 
"Sex", "Weight"), class = "data.frame", row.names = c(NA, -15L
))

1 个答案:

答案 0 :(得分:3)

使用正确的类(数字,因子)分配到数据列,您可以这样做:

library(ggplot2)

DF = structure(list(Group = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 
2L, 3L, 3L, 3L, 3L, 3L), Sex = c(1L, 2L, 2L, 1L, 1L, 2L, 2L, 
1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L), Weight = structure(c(6L, 1L, 
11L, 10L, 4L, 12L, 13L, 2L, 8L, 5L, 3L, 12L, 2L, 7L, 9L), .Label = c("", 
".", "124", "127", "129", "140", "141", "147", "148", "154", 
"160", "182", "192"), class = "factor")), .Names = c("Group", 
"Sex", "Weight"), class = "data.frame", row.names = c(NA, -15L
))

str(DF)
#'data.frame':  15 obs. of  3 variables:
# $ Group : int  1 1 1 1 1 2 2 2 2 2 ...
# $ Sex   : int  1 2 2 1 1 2 2 1 1 1 ...
# $ Weight: Factor w/ 13 levels "",".","124","127",..: 6 1 11 10 4 12 13 2 8 5 ...

#The Weight column is currently of class factor that needs to converted to 
#class numeric by first converting to character class and replacing "." by ""


DF$Weight = as.numeric(gsub("[.]","",as.character(DF$Weight)))

#Sex variable should be converted to factor, 
#If 1 is considered as FeMale and 2 as Male

DF$Sex = ifelse(DF$Sex==1,"FeMale","Male")

DF$Sex <- as.factor(DF$Sex)

gg <- ggplot(DF, aes(x=Sex, y=Weight)) + 
  geom_boxplot() + facet_wrap(~Group) + ggtitle("Weight vs Sex for various Groups") +
  theme(plot.title = element_text(size=14, face="bold"))
gg

enter image description here