gpt4 book ai didi

r - ggplot2 中的多个直方图

转载 作者:行者123 更新时间:2023-12-02 07:38:31 25 4
gpt4 key购买 nike

这是我的数据的一小部分:

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

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

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

结果是:

Histogram with base R graphics

我可以让它看起来更好,但我更感兴趣的是学习如何使用 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))
}
}

但我想有一种更简单的方法可以做到这一点?

最佳答案

您可以尝试 gridExtra 中的 grid.arrange()包裹;即,将绘图存储在列表中(例如 qplt),然后使用

do.call(grid.arrange, qplt)

其他想法:通过考虑 data.frame(使用 melt),在 ggplot2 中使用分面(sex*variable)。

作为旁注,在我看来,最好使用堆叠条形图或克利夫兰点图来显示项目响应频率。 (我在 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

关于r - ggplot2 中的多个直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6200088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com