本文介绍了使用position_dodge时发出geom_text的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到答案,但无法复制它。
我得到这样的数据:
df = data.frame( x = rep(sample(letters,4),2),
y = round(runif(8,1,100),0),
z = c(rep(group1,4),rep group2,4)))
#然后我添加一个'percent'列如下:
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])
#然后我转换成这样:
df $ perc = paste(round(df $ perc * 100,1),%,sep =)
#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)
结果:
/ p>
我无法弄清楚我做错了什么。
解决方案
只是一个小小的改变就解决了这个问题。您需要在 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)
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:
I can't figure out what I did wrong.
解决方案
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)
这篇关于使用position_dodge时发出geom_text的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!