使用position_dodge时使用geom_text时出现问题

knl*_*knl 8 r ggplot2

我看到了这个答案,但无法复制它.

我得到这样的数据:

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)
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

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

bde*_*est 14

只需一个小改动即可解决问题.您需要group=xgeom_text(aes(...))通话中指定.

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 或者将 `fill = x` 移动到 `ggplot` 中的“顶层”。然后这个躲避变量也被继承到`geom_text`。`躲避<-位置躲避(宽度= 1)`; `ggplot(df, aes(z, y, fill = x, label = perc)) + geom_bar(position = dodge, stat = "identity") + geom_text(position = dodge, size = 4)`。您还避免为每个 `geom` 重复 `aes(z, y,`。 (2认同)