使用ggplot中的geom_text标记条形图

时间:2013-08-29 18:33:58

标签: r ggplot2

我用以下代码创建了这个图:

library(ggplot2); library(reshape2); library(plyr)

likert <- data.frame(age = c(rep("young", 5), rep("middle", 5), rep("old", 5)),
                     score1 = c(rep("unlikely", 1), rep("likely", 1), rep("very likely", 13)),
                     score2  = c(rep("disagree", 6), rep("neutral", 4), rep("agree", 5)),
                     score3 = c(rep("no", 5), rep("maybe", 7), rep("yes", 3)))

meltedLikert <- melt(dlply(likert, .(age), function(x) llply(x, table)))

names(meltedLikert) <- c("score", "count", "variable", "age")

ggplot(meltedLikert[meltedLikert$variable != "age",], aes(variable, count, fill=score)) + 
  geom_bar(position="dodge", stat="identity") +
  geom_text(data=data.frame(meltedLikert), aes(variable, count, group=score, label=meltedLikert$score), size=4) +
  facet_grid(age ~ .)

enter image description here

如何标记位置文字,以便score的每个标签都位于每个栏顶部variable的相应栏上?

1 个答案:

答案 0 :(得分:12)

根据linked question中的答案,将position = position_dodge(width=0.9)添加到geom_text个致电符号的行中:

ggplot(meltedLikert[meltedLikert$variable != "age",], 
       aes(variable, count, fill=score)) + 
  geom_bar(position="dodge", stat="identity") +
  geom_text(data=data.frame(meltedLikert), 
            aes(variable, count, group=score, label=meltedLikert$score), 
            position = position_dodge(width=0.9),
            size=4) +
  facet_grid(age ~ .)

enter image description here

但是,我还想指出其他一些事情。您不应在meltedLikert$score电话中使用aes();您应该只引用数据框中以data传递的内容。此外,meltedLikert已经是data.frame,因此无需调用data.frame()(但不会造成任何伤害)。

真正的改进在于如何创建表格。请考虑一下:

tabulatedLikert <- ldply(likert[-1], function(sc) {
  as.data.frame(table(age = likert$age, score = sc))
})
ggplot(tabulatedLikert, aes(x=.id, y=Freq, fill=score)) +
  geom_bar(position="dodge", stat="identity") +
  geom_text(aes(label=score), position=position_dodge(width=0.9), size=4) +
  facet_grid(age ~ .)

enter image description here

您可以通过将它们固定在原始数据中来修复条形的顺序:

likert2 <- mutate(likert,
                  score1 = factor(score1, levels=c("unlikely", "likely", "very likely")),
                  score2 = factor(score2, levels=c("disagree", "neutral", "agree")),
                  score3 = factor(score3, levels=c("no", "maybe", "yes")))
tabulatedLikert2 <- ldply(likert2[-1], function(sc) {
  as.data.frame(table(age = likert2$age, score = sc))
})
ggplot(tabulatedLikert2, aes(x=.id, y=Freq, fill=score)) +
  geom_bar(position="dodge", stat="identity") +
  geom_text(aes(label=score), position=position_dodge(width=0.9), size=4) +
  facet_grid(age ~ .)

enter image description here

当然,在这一点上,颜色实际上并没有添加任何东西,因为所有东西都直接在图表上标记,所以我只是完全摆脱它们。

ggplot(tabulatedLikert2, aes(x=.id, y=Freq, group=score)) +
  geom_bar(position="dodge", stat="identity", fill="gray70") +
  geom_text(aes(label=score), position=position_dodge(width=0.9), size=4) +
  facet_grid(age ~ .)

enter image description here