2016-06-08 77 views
3

我有两个不同数据集,它们具有不同数量的观察值。我想在同一个图上绘制两个盒形图,因此比较起来更容易。我可以绘制一个boxplot,但如果没有它们并排,很难发现任何差异。同一图上的两个箱形图

我有一些假的数据。

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 

我不知道如何绘制这个图,所以我没有一个例子。我会尽我所能来描述情节。我想在同一个图上绘制变量1的A组和B组。因此,在一张图上,我将为A组提供一个boxplot,而另一个boxblot则充满来自V1的数据。所以这两个箱子将并排。有5个变量,我会有5个图表,每个图表并排2个箱形图。如果我不清楚,请告诉我。谢谢。

回答

3

ggplot对于“长格式”数据(例如,对于值,变量和组中的每一列均有效),效果最佳。你可以重新安排你的数据如下:

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

enter image description here

+0

正是我要找的!我可以问一下'facet_wrap(〜ind,scales ='free_y')'是什么意思? – pineapple

+0

'facet_wrap'将图分成多个面板,在这种情况下,我们指定我们希望按照'ind'(当我们使用'stack'时给出的变量列的缺省名称来分隔它们。否则变量将被汇集。'scales ='free_y''允许为每个面板优化y轴限制(参见'?facet_wrap')。 – jbaums

3

的我想出的解决方案是结合两个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) 

enter image description here

2

假设你的数据集的名称是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()

enter image description here

根据需要标签。

-1
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 
1
# 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) 

enter image description here

相关问题