我正在尝试使用ggplot
将百分比叠加到条形图上。我尝试过失败的方法:
使用geom_text:
p <- ggplot(data, aes(x = factor(data[[variable1]]) ), environment = environment() )
p <- p + geom_bar(aes(y = ..count../sum(..count..)), position = modo)
p <- p + geom_text( aes(labels = ..count../sum(..count..)) , vjust = -0.2)
p <- p + scale_y_continuous(labels = percent_format())
我收到错误消息:
eval(expr,envir,enclos)中的错误:找不到对象'count'
正如建议here,我尝试了stat_bin函数,但是规模搞砸了,我丢失了条(根据新的比例,我猜它们仍然存在,但只是不可见):
p <- ggplot(data, aes(x = factor(data[[variable1]]) ), environment = environment() )
p <- p + geom_bar(aes(y = ..count../sum(..count..)), position = modo)
p <- p + stat_bin( aes(label = ..count../sum(..count..) ) , vjust = -0.2, geom ="text" )
p <- p + scale_y_continuous(labels = percent_format())
这就是我得到的:
关于如何解决这个问题的任何线索?
答案 0 :(得分:2)
在这里回答我自己的问题:
我必须映射y值。我还必须将标签值乘以100才能获得一致的百分比。
p <- ggplot(data, aes(x = factor(data[[variable1]]) ), environment = environment() )
p <- p + geom_bar(aes(y = ..count../sum(..count..)), position = modo)
p <- p + scale_y_continuous(labels = percent_format())
p <- p + stat_bin( aes(y = ..count../sum(..count..), label = paste( round( 100 * ..count../sum(..count..)), "%" ) ), vjust = -0.2, geom ="text" )