同一张图上的两个箱线图

Two boxplots on the same graph

我有两个不同的数据集,它们具有不同数量的观察值。我想在同一张图上绘制两个箱线图,以便更容易进行比较。我可以绘制一个箱线图,但如果没有将它们并排放置,就很难发现任何差异。

我有一些假数据。

Group A
V1    V2   V3    V4     V5
6.5   2    11    0.5    6
7     1    8     0.34   8
5.4   4    7.8   0.45   5
3.4   6    9.1   0.72   5

Group B
V1    V2   V3    V4     V5
5.0   5    9     0.4    7
2     7    5.2   0.69   5
3.2   2    2.9   0.79   2
6.8   9    6.5   0.43   6
4.7   3    3.8   0.49   4
5.5   4    7.4   0.94   3

我不知道如何绘制图表,所以我没有示例。我会尽力描述情节。我想在同一张图上绘制 A 组和 B 组的变量 1。因此,在一张图表上,我会为 A 组绘制一个箱线图,为 B 组绘制另一个箱线图,其中填充了来自 V1 的数据。所以这两个箱线图会并排。如果有 5 个变量,我将有 5 个图表,每个图表有 2 个并排的箱线图。如果我不清楚,请告诉我。谢谢你。

ggplot 最适合 "long format" 数据(例如,每个值、变量和组都有一列)。您可以按如下方式重新排列数据:

A <- read.table(text='V1    V2   V3    V4     V5
6.5   2    11    0.5    6
7     1    8     0.34   8
5.4   4    7.8   0.45   5
3.4   6    9.1   0.72   5', header=TRUE)

B <- read.table(text='V1    V2   V3    V4     V5
5.0   5    9     0.4    7
2     7    5.2   0.69   5
3.2   2    2.9   0.79   2
6.8   9    6.5   0.43   6
4.7   3    3.8   0.49   4
5.5   4    7.4   0.94   3', header=TRUE)

d <- rbind(cbind(stack(A), group='A'), cbind(stack(B), group='B'))

前几行如下所示:

head(d)

##   values ind group
## 1    6.5  V1     A
## 2    7.0  V1     A
## 3    5.4  V1     A
## 4    3.4  V1     A
## 5    2.0  V2     A
## 6    1.0  V2     A

现在我们可以这样画了:

library(ggplot2)
ggplot(d, aes(group, values)) + 
  geom_boxplot() +
  facet_wrap(~ind, scales='free_y')

我想到的解决方案是将两个 data.frame 和一个指示观察属于哪个组的变量组合起来。然后,您可以使用 reshape2 中的 melt 函数将数据转换为 data.frame 准备绘图。您可以使用 facet_gridfacet_wrap 为不同的变量创建单独的图。这是一种方法:

library(ggplot2)
library(reshape2)

# Combine two data.frame
df <- rbind(GroupA, GroupB)

# Create variable Group
df$Group <- rep(c("A", "B"), c(dim(GroupA)[1], dim(GroupB)[1]))

# Transform to long format
df <- melt(df, "Group")

ggplot(df, aes(x=Group, y=value)) + geom_boxplot() + facet_grid(~ variable)

假设你的数据集名称是grpa(A组)和grpb(B组)。先给他们每个人加一个变量Group

grpa$Group <-"A"

grpb$Group <-"B"

然后将它们组合成一个数据帧

combined <- rbind(grpa,grpb)

然后使用 ggplot 绘图:

ggplot(combined,aes(x= factor(Group), y=V1))+geom_boxplot()

根据需要添加标签。

   par(mfrow=c(1,2))
   summary(A)
   summary(B)
   boxplot(A,ylim=summary(A)[[1]][1]) ##not sure about this just find where y is min
   boxplot(B,ylim=summary(B)[[1]][1]) ## still not sure
    ## adjusts the ylims in a way so that they are easy to compare you can also use boxplot(A,B) but that would make the graph look weird
# Adding a variable to the dataframes Group_A & Group_B as done from pervious users
Group_A$fac <- "A"
Group_B$fac <- "B"
Group_c <- rbind(Group_A,Group_B)
df <- melt(Group_c)

#You can plot the same in bwplot from library(lattice) 

bwplot(value~fac|variable,data=df,scales=list(relation="free"),as.table=T)