r - 让 ggplot2 直方图在 y 轴上显示类别百分比

标签 r ggplot2

library(ggplot2)
data = diamonds[, c('carat', 'color')]
data = data[data$color %in% c('D', 'E'), ]

我想比较颜色 D 和 E 的克拉直方图,并在 y 轴上使用分类百分比。我尝试过的解决方案如下:

解决方案1:
ggplot(data=data, aes(carat, fill=color)) +  geom_bar(aes(y=..density..), position='dodge', binwidth = 0.5) + ylab("Percentage") +xlab("Carat")

enter image description here

这不太正确,因为 y 轴显示了估计密度的高度。

解决方案2:
 ggplot(data=data, aes(carat, fill=color)) +  geom_histogram(aes(y=(..count..)/sum(..count..)), position='dodge', binwidth = 0.5) + ylab("Percentage") +xlab("Carat")

enter image description here

这也不是我想要的,因为用于计算 y 轴上比率的分母是 D + E 的总数。

有没有办法用ggplot2的堆叠直方图显示分类百分比?也就是说,不是在 y 轴上显示 (# of obs in bin)/count(D+E),我希望它显示 (# of obs in bin)/count(D) 和 (# of obs in bin)/count(E) 分别用于两个颜色类别。谢谢。

最佳答案

您可以使用 ..group.. 按组缩放它们。用于对 ..count.. 进行子集化的特殊变量向量。由于所有的点,它非常丑陋,但它在这里

ggplot(data, aes(carat, fill=color)) +
  geom_histogram(aes(y=c(..count..[..group..==1]/sum(..count..[..group..==1]),
                         ..count..[..group..==2]/sum(..count..[..group..==2]))*100),
                 position='dodge', binwidth=0.5) +
  ylab("Percentage") + xlab("Carat")

enter image description here

关于r - 让 ggplot2 直方图在 y 轴上显示类别百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31200254/

相关文章:

r - ggplot : Save multiple plots in one pdf with the same plot proportions

r - 如何在 map 上以最少的重叠绘制网络

r - 更改 ggplot 上的 geom_bar 宽度

r - 使用 nlm 函数对多个变量进行优化

java - 如何在Windows中从java自动启动rserve

R,试图将整数向量转换为特定的二进制矩阵

r - ggplot2 facet_grid() strip_text_x() 基于因子的不同颜色

r - 将不同长度的向量依次合并成一个矩阵

r - 使用 coord_equal() 时垂直对齐不同高度的多面 ggplot

r - 绘制 R 地区粮农组织捕鱼区 map