我正在geom_density使用数据框制作一系列密度图,并使用条件显示它facet_wrap,如:
ggplot(iris) + geom_density(aes(x=Sepal.Width, colour=Species, y=..count../sum(..count..))) + facet_wrap(~Species)
Run Code Online (Sandbox Code Playgroud)
当我这样做时,y轴刻度似乎不代表Species面板中每个的百分比,而是所有物种中所有总数据点的百分比.
我的问题是:我怎样才能使..count..变量in geom_density指的Species是每个面板每组中的项目数,以便面板virginica的y轴对应于" virginica数据点的分数"?
另外,有没有办法让ggplot2输出它用于的值..count..,sum(..count..)以便我可以验证它使用的是什么数字?
编辑:我误解了geom_density它看起来甚至单个Species,..count../sum(..count..)不是百分比:
ggplot(iris[iris$Species == 'virginica',]) + geom_density(aes(x=Sepal.Width, colour=Species, y=..count../sum(..count..))) + facet_wrap(~Species)
Run Code Online (Sandbox Code Playgroud)
所以我修改过的问题:我怎样才能将密度图作为每个bin中数据的一部分?我必须使用stat_density这个或geom_histogram?我只想让y轴成为数据点的百分比/分数
不幸的是,你要求ggplot2做的是为每个方面定义单独的y,它在语法上不能做AFAIK.
所以,为了回应你在评论主题中提到你"只是想要一个根本上的直方图",我建议改为使用geom_histogram或者,如果你偏向于行而不是条形,geom_freqpoly:
ggplot(iris, aes(Sepal.Width, ..count..)) +
geom_histogram(aes(colour=Species, fill=Species), binwidth=.2) +
geom_freqpoly(colour="black", binwidth=.2) +
facet_wrap(~Species)
Run Code Online (Sandbox Code Playgroud)

**注意:在我上面的例子中,geom_freqpoly也可以代替geom_histogram.为了提高效率,我在一个图中添加了两个.
希望这可以帮助.
编辑:好吧,我设法找到了一个快速而肮脏的方式来获得你想要的东西.它要求您安装和加载plyr.提前道歉; 就RAM使用而言,这可能不是最有效的方法,但它确实有效.
首先,让我们在开放中获取虹膜(我使用RStudio所以我习惯在窗口中看到所有对象):
d <- iris
Run Code Online (Sandbox Code Playgroud)
现在,我们可以ddply用来计算属于每个独特测量的个体数量,这将成为你的x轴(这里我使用Sepal.Length而不是Sepal.Width,给自己更多的范围,只是为了看到更大的绘制时组之间的差异).
new <- ddply(d, c("Species", "Sepal.Length"), summarize, count=length(Sepal.Length))
Run Code Online (Sandbox Code Playgroud)
请注意,ddply根据引用的变量自动对输出data.frame进行排序.
然后我们可以将data.frame分成每个独特的条件 - 在虹膜的情况下,三个物种中的每一个(我确信有一个更平滑的方式来解决这个问题,如果你正在使用它真的是大量的数据不建议继续创建相同data.frame的子集,因为你可以最大化你的RAM)...
set <- new[which(new$Species%in%"setosa"),]
ver <- new[which(new$Species%in%"versicolor"),]
vgn <- new[which(new$Species%in%"virginica"),]
Run Code Online (Sandbox Code Playgroud)
...和使用ddply再计算个人每次测量下下降的比例,但单独为每个物种.
prop <- rbind(ddply(set, c("Species"), summarize, prop=set$count/sum(set$count)),
ddply(ver, c("Species"), summarize, prop=ver$count/sum(ver$count)),
ddply(vgn, c("Species"), summarize, prop=vgn$count/sum(vgn$count)))
Run Code Online (Sandbox Code Playgroud)
然后我们将所需的所有内容放入一个数据集中,并从工作区中删除所有垃圾.
new$prop <- prop$prop
rm(list=ls()[which(!ls()%in%c("new", "d"))])
Run Code Online (Sandbox Code Playgroud)
我们可以在y上以特定方面的比例制作我们的数字.请注意,我现在正在使用,geom_line因为ddply已经自动订购了data.frame.
ggplot(new, aes(Sepal.Length, prop)) +
geom_line(aes(colour=new$Species)) +
facet_wrap(~Species)
Run Code Online (Sandbox Code Playgroud)

# let's check our work. each should equal 50
sum(new$count[which(new$Species%in%"setosa")])
sum(new$count[which(new$Species%in%"versicolor")])
sum(new$count[which(new$Species%in%"versicolor")])
#... and each of these should equal 1
sum(new$prop[which(new$Species%in%"setosa")])
sum(new$prop[which(new$Species%in%"versicolor")])
sum(new$prop[which(new$Species%in%"versicolor")])
Run Code Online (Sandbox Code Playgroud)