R 使用ggplot2绘制具有百分比的多个数据集的直方图
我有四个数据集,我想在同一个图上绘制所有数据的直方图。我把所有的数据放在一个数据框中。我还可以在一个图上绘制直方图。然而,我在绘制百分比而不是计数时遇到了困难。当我使用下面的代码时,它将百分比绘制为所有计数的总和,但我更希望百分比是相对于每个数据集的。这可能吗R 使用ggplot2绘制具有百分比的多个数据集的直方图,r,ggplot2,histogram,percentage,R,Ggplot2,Histogram,Percentage,我有四个数据集,我想在同一个图上绘制所有数据的直方图。我把所有的数据放在一个数据框中。我还可以在一个图上绘制直方图。然而,我在绘制百分比而不是计数时遇到了困难。当我使用下面的代码时,它将百分比绘制为所有计数的总和,但我更希望百分比是相对于每个数据集的。这可能吗 all <- rbind(data.frame(fill = "A", Events = A$Events), data.frame(fill = "B", Events = B$Events), data.fr
all <- rbind(data.frame(fill = "A", Events = A$Events),
data.frame(fill = "B", Events = B$Events),
data.frame(fill = "C", Events = C$Events),
data.frame(fill = "D", Events = D$Events)
ggplot(all,aes(x=Events, fill = fill)) +
geom_histogram(aes(y = ..count../sum(..count..)), position = 'dodge')
您很接近,但需要使用
(…密度..)*binwidth
而不是。count../sum(…count..)
旧答案
以下是一个例子:
library(ggplot2)
ggplot(mtcars,aes(x=mpg, fill = as.factor(cyl))) +
geom_histogram(aes(y = ..density..), position = 'dodge', binwidth=5)
作为检查,将binwidth调整为100,每个列的值为0.01(100%/100=0.01)
(编辑)下面是另一个示例,使用过于简化的数据集突出显示结果:
library(data.table)
# Calculate the average miles per gallon by number of cylinders
mtcars_avg <- as.data.table(mtcars)[,
list(mpg_avg=mean(mpg)),
by=list(cyl=as.factor(cyl))][order(cyl)][order(cyl)]
mtcars_avg
# cyl mpg_avg
#1: 4 26.66364
#2: 6 19.74286
#3: 8 15.10000
# OP version, with unwanted results of 33% per color (cyl)
ggplot(mtcars_avg, aes(x=mpg_avg, fill=cyl)) +
geom_histogram(aes(y = ..count../sum(..count..)), position = 'dodge', binwidth=1)
你也可以考虑使用<代码> GeoMeStime代替:
ggplot(mtcars,aes(x=mpg, fill = as.factor(cyl))) + geom_density(alpha=0.5)
这个binwidth是必需的,因为根据定义,整数和为1。 基本上,箱宽的
x
增加导致箱宽的y
变化1/x
-箱宽更大,因此必须降低高度才能获得相同的面积
因此,要恢复百分比,您必须通过将y
乘以bw
来纠正此错误
Aa一个简单的例子,想象一下一点:
- 基本的“
”代码将为您提供百分比,因为.density..
,即bw*p=1
1*1=1
- 如果将
更改为2,则“bw
”代码将在y轴上显示:.density..
bw*y=1=>y=1/bw=0.5
- 为了获得
轴上的百分比,必须乘以y
bw
library(ggplot2)
ggplot(mtcars,aes(x=mpg, fill = as.factor(cyl))) +
geom_histogram(aes(y = ..density..), position = 'dodge', binwidth=5)
library(data.table)
# Calculate the average miles per gallon by number of cylinders
mtcars_avg <- as.data.table(mtcars)[,
list(mpg_avg=mean(mpg)),
by=list(cyl=as.factor(cyl))][order(cyl)][order(cyl)]
mtcars_avg
# cyl mpg_avg
#1: 4 26.66364
#2: 6 19.74286
#3: 8 15.10000
# OP version, with unwanted results of 33% per color (cyl)
ggplot(mtcars_avg, aes(x=mpg_avg, fill=cyl)) +
geom_histogram(aes(y = ..count../sum(..count..)), position = 'dodge', binwidth=1)
# ..density.. version, which shows the desired results of 100% per color (cyl)
ggplot(mtcars_avg, aes(x=mpg_avg, fill=cyl)) +
geom_histogram(aes(y = ..density..), position = 'dodge', binwidth=1)
ggplot(mtcars,aes(x=mpg, fill = as.factor(cyl))) + geom_density(alpha=0.5)