在使用facet_wrap分组时填充条形有问题使用此data.frame:
library(ggplot2)
library(gridExtra)
set.seed(1234)
testDat <- data.frame(answer=factor(sample(c("yes", "no"), 60, replace=TRUE)),
which=factor(sample(c("q1", "q2", "q3"), 60, replace=TRUE)))
我想绘制由变量分组的答案 . 这给了我绝对值:
ggplot(testDat, aes(x=answer)) +
geom_bar(aes(fill=answer)) + facet_wrap(~which)
这给了我相对的 Value . 但不是每组:
ggplot(testDat, aes(x=answer)) +
geom_bar(aes(y=(..count..)/sum(..count..), fill=answer)) + facet_wrap(~which)
搜索答案我检测到这个以绘制每组的相对值 . 但填充颜色不再起作用
ggplot(testDat, aes(x=answer)) +
geom_bar(aes(y=(..count..)/sum(..count..), group=which, fill=answer)) + facet_wrap(~which)
它适用于“哪个”而不是“回答”的三个不同值
ggplot(testDat, aes(x=answer)) +
geom_bar(aes(y=(..count..)/sum(..count..), group=which, fill=which)) + facet_wrap(~which)
有关如何填充酒吧的任何建议?
p1<-ggplot(testDat, aes(x=answer)) + geom_bar(aes(y=(..count..)/sum(..count..), group=which, fill=answer)) + facet_wrap(~which)
p2<-ggplot(testDat, aes(x=answer)) + geom_bar(aes(y=(..count..)/sum(..count..), group=which, fill=which)) + facet_wrap(~which)
grid.arrange(p1,p2)
2 回答
有一种方法可以使用ggplot作为mentioned in this question的请求进行聚合 . 但是,它需要使用PANEL variable that isn't documented therefore Hadley recomended not to use it .
这是一种使用
data.table
进行聚合的方法 . 我还在情节中添加了百分比标签 .这是你的想法吗?
不幸的是,当在美学映射中使用时,聚合诸如
sum(...), min(...), max(...), range(...)
等的功能并不尊重由方面暗示的分组 . 因此,虽然..count..
在单独使用时(在您的分子中)正确地进行了子集化,但sum(..count..)
给出了整个数据集的总和 . 这就是为什么(..count..)/sum(..count..)
给出总数的分数,而不是该分数的分数 .我所知道的唯一方法就是如上所述创建一个腋下表 .