r – 使用position_dodge时发生geom_text问题

我看到了 this的答案,但无法复制它.

我得到这样的数据:

df = data.frame(x = rep(sample(letters,4),2),y = round(runif(8,1,100),0),z = c(rep("group1",rep("group2",4)))

# I then add a 'percent' column like so:

df$perc[1:4] = df$y[1:4] / sum(df$y[1:4])
df$perc[5:8] = df$y[5:8] / sum(df$y[5:8])

# Which I then convert like so:
df$perc = paste(round(df$perc * 100,1),"%",sep="")

# The ggplot:
library(ggplot2)

ggplot(df) + 
geom_bar(aes(z,y,fill=x),position="dodge",stat="identity") + 
geom_text(aes(z,label=perc),position=position_dodge(width=1),size=4)

结果:

我无法弄清楚我做错了什么.

解决方法

只需一个小改动即可解决问题.您需要在geom_text(aes(…))调用中指定group = x.
ggplot(df) + 
geom_bar(aes(z,label=perc,group=x),size=4)

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效