0

我正在尝试使用 ggplot2 绘制直方图,y 轴为百分比,x 轴为数值。

我的数据和脚本示例如下所示(如下),并持续了大约 100,000 行(或更多)。

A    B
0.2  x
1    y
0.995    x
0.5  x
0.5  x
0.2  y
ggplot(data, aes(A, colour=B)) + geom_bar() +stat_bin(breaks=seq(0,1, by=0.05)) + scale_y_continuous(labels = percent)

我想知道 B 值在 A 值的每个 bin 中分布的百分比,而不是每个 A 值的 B 值数量。

现在的代码给了我一个 y 轴为 15000 的 y 轴。y 轴应该是百分比(0-100)。

4

1 回答 1

2

这是你想要的吗?我假设您的数据框称为 df:

# calculate proportions of B for each level of A
df2 <- as.data.frame(with(df, prop.table(table(A, B))))
df2
#       A B      Freq
# 1   0.2 x 0.1666667
# 2   0.5 x 0.3333333
# 3 0.995 x 0.1666667
# 4     1 x 0.0000000
# 5   0.2 y 0.1666667
# 6   0.5 y 0.0000000
# 7 0.995 y 0.0000000
# 8     1 y 0.1666667

ggplot(data = df2, aes(x = A, y = Freq, fill = B)) +
geom_bar(stat = "identity", position = position_dodge())

在此处输入图像描述

于 2013-09-19T18:08:12.127 回答