在ggplot2中绘制多个直方图

13

以下是我数据的一小部分:

dat <-structure(list(sex = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("male", 
"female"), class = "factor"), A = c(1, 2, 0, 2, 1, 2, 2, 0, 2, 
0, 1, 2, 2, 0, 0, 2, 0, 0, 0, 2), B = c(0, 0, 0, 0, 0, 2, 0, 
0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0), C = c(1, 2, 1, 0, 0, 
2, 1, 1, 0, 1, 1, 0, 1, 2, 1, 2, 0, 2, 1, 2), D = c(2, 2, 0, 
2, 2, 2, 1, 0, 1, 1, 1, 0, 1, 2, 0, 0, 1, 1, 1, 0), E = c(0, 
0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 2, 2), F = c(2, 
2, 1, 2, 1, 2, 2, 0, 1, 2, 0, 1, 2, 2, 0, 1, 2, 2, 2, 2)), .Names = c("sex", 
"A", "B", "C", "D", "E", "F"), variable.labels = structure(c("sex", 
"zenuwac", "panieke", "gespann", "rustelo", "angstig", "onzeker"
), .Names = c("sex", "anx01", "anx02", "anx03", "anx04", "anx05", 
"anx06")), codepage = 20127L, row.names = c(NA, 20L), class = "data.frame")

一个数据框,其中包含男性和女性在六个3点变量上的分数。现在我想创建一个图表,该图表显示男性和女性在一个网格中每个变量的分数直方图。例如,我可以这样做:

layout(matrix(1:12,6,2,byrow=TRUE))
par(mar=c(2,1,2,1))
for (i in 1:6) for (s in c("male","female")) hist(dat[dat$sex==s,i+1],main=paste("item",names(dat)[i+1],s))

导致如下结果:

基于R基础图形的直方图

我可以让它看起来更好,但我更想学习如何使用ggplot2。所以我的问题是,如何使用ggplot2创建一个漂亮的版本?我已经尝试了一件事情:

library("ggplot2")
grid.newpage()
pushViewport(viewport(layout = grid.layout(6, 2)))   
for (s in 1:2)
{
    for (i in 1:6)
    {
        p <- qplot(dat[dat$sex==c("male","female")[s],i+1]+0.5, geom="histogram", binwidth=1)
        print(p, vp = viewport(layout.pos.row = i, layout.pos.col = s))
    }
}

但我猜应该有一个更简单的方法吧?

2个回答

19

您可以尝试使用gridExtra包中的grid.arrange()函数;即,将您的绘图存储在一个列表中(例如qplt),并使用该函数

do.call(grid.arrange, qplt)

其他想法:在ggplot2中使用facetting(sex*variable),考虑使用数据框(使用melt)。

顺便提一句,我认为最好使用堆积条形图或Cleveland点图来显示项目响应频率。(我在CrossValidated上提供了一些想法。)


为了完整起见,这里提供一些实现想法:

# simple barchart
ggplot(melt(dat), aes(x=as.factor(value), fill=as.factor(value))) + 
  geom_bar() + facet_grid (variable ~ sex) + xlab("") + coord_flip() + 
  scale_fill_discrete("Response")

enter image description here

my.df <- ddply(melt(dat), c("sex","variable"), summarize, 
               count=table(value))
my.df$resp <- gl(3, 1, length=nrow(my.df), labels=0:2)

# stacked barchart
ggplot(my.df, aes(x=variable, y=count, fill=resp)) + 
  geom_bar() + facet_wrap(~sex) + coord_flip()

enter image description here

# dotplot
ggplot(my.df, aes(x=count, y=resp, colour=sex)) + geom_point() + 
  facet_wrap(~ variable)

enter image description here


4

跟随chl的例子,以下是使用ggplot复制基础图形的方法。我也建议看一下点图:

library(ggplot2)
dat.m <- melt(dat, "sex") 

ggplot(dat.m, aes(value)) + 
  geom_bar(binwidth = 0.5) + 
  facet_grid(variable ~ sex)

(+1) 好的,最终我得到了类似于 ggplot(subset(melt(dat), as.numeric(variable)==i), aes(x=as.factor(value))) + geom_bar() + facet_grid (. ~ sex) + xlab("") 的东西(在关于 variable 级别的 for 循环内)。将 value 转换为因子可以避免杂乱的 x 单位。 - chl
@chl - 把value转换成因子是个好主意。我不确定OP的完整数据集是否会填补这些尴尬的空白,但无论如何,这是一个很好的技巧。 - Chase

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接