【问题标题】:Issue with geom_text when using position_dodge使用 position_dodge 时出现 geom_text 问题
【发布时间】:2015-06-04 02:52:21
【问题描述】:

我看到了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)

结果:

我不知道我做错了什么。

【问题讨论】:

标签: r ggplot2


【解决方案1】:

只需一个小改动即可解决问题。您需要在 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)

【讨论】:

  • 或将fill = x 移动到ggplot 中的“顶层”。然后这个躲避变量也被继承给geom_textdodge <- position_dodge(width = 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,
猜你喜欢
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 2015-03-07
  • 1970-01-01
  • 2011-06-14
  • 2019-08-11
  • 2021-10-30
相关资源
最近更新 更多