Sac*_*amp 11 r histogram ggplot2
这是我的数据的一小部分:
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")
Run Code Online (Sandbox Code Playgroud)
一个数据框,在六个三点变量上有多个男性和女性.现在我想创建一个图表,显示网格中男性和女性的每个变量得分的直方图.例如,我可以这样做:
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))
Run Code Online (Sandbox Code Playgroud)
这导致:
我可以让这个看起来更好但我更感兴趣的是学习如何使用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))
}
}
Run Code Online (Sandbox Code Playgroud)
但我想有一个更简单的方法来做到这一点?
chl*_*chl 16
您可以尝试grid.arrange()
从gridExtra包; 即,将您的情节存储在一个列表中(比如说qplt
),然后使用
do.call(grid.arrange, qplt)
Run Code Online (Sandbox Code Playgroud)
其他想法:sex*variable
通过考虑data.frame(使用melt
)在ggplot2()中 使用facetting .
作为旁注,最好使用堆叠条形图或克利夫兰的dotplot来显示项目响应频率,IMO.(我在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")
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
# dotplot
ggplot(my.df, aes(x=count, y=resp, colour=sex)) + geom_point() +
facet_wrap(~ variable)
Run Code Online (Sandbox Code Playgroud)