R -柱状图ggplot2错误频率



大家好,我对ggplot2很不满意。

我正在尝试制作一个直方图来表示例如:性别(男性和女性= y)与癌症(C)的百分比按5个年龄类别(a = x)。

pp <- ggplot(data=base, aes(x=AGE, y=factor(C), fill=Sex)) + 
  geom_bar(aes(y = (..count..)/sum(..count..)))+
  scale_fill_grey()+
  theme_bw()
pp

我有直方图,但错误的频率。有人能告诉我为什么吗?

我很难自己解决这个问题。

Thanks in advance

可以使用geom_histogram:

PP <- ggplot(base[base$C==TRUE,], aes(x=AGE, fill=Sex))
PP <- PP + geom_histogram()

注:我不知道C是否被编码为布尔值。

UPDATE - frequency的表达式如下:

PP <- ggplot(base[base$C==TRUE,], aes(x=AGE, fill=Sex))
PP <- PP + geom_histogram(aes(y = ..density..))

更新- OP的澄清表明他毕竟不是在寻找直方图:

因此,对于所需的条形图,您需要稍微重新排列数据并创建汇总版本,例如,通过使用plyr::ddply():

require(plyr)
baseA <- ddply(base, .(AGE,Sex), summarize, cancerShare=sum(C==TRUE)/length(C))

之后,我们可以绘制如下的条形图:

g <- ggplot(baseA,aes(x=as.factor(AGE),y=cancerShare,fill=Gender))
g <- g + geom_bar(stat="identity",position="dodge")
g

最新更新