Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

r - Issue with geom_text when using position_dodge

I saw this answer but couldn't replicate it.

I get my data like this:

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)

Result:

enter image description here

I can't figure out what I did wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just one minor change solves the issue. You need to specify group=x inside your geom_text(aes(...)) call.

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)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...