[英]geom_text not properly positioned when using position_dodge(preserve=“single”) in bar plot
[英]Issue with geom_text when using position_dodge
我看到了这个答案,但无法复制。
我得到这样的数据:
df = data.frame(x = rep(sample(letters, 4), 2),
y = round(runif(8,1,100),0),
z = c(rep("group1",4), 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,y,label=perc), position=position_dodge(width=1), size=4)
结果:
我不知道我做错了什么。
只需进行一个较小的更改即可解决此问题。 您需要在geom_text(aes(...))
调用中指定group=x
。
ggplot(df) +
geom_bar(aes(z, y, fill=x), position=position_dodge(width=1), stat="identity") +
geom_text(aes(z,y,label=perc, group=x), position=position_dodge(width=1), size=4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.