使用ggplot中的geom_text标记条形图

luc*_*ano 6 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 ~ .)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

Bri*_*ggs 13

根据链接问题中的答案,添加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 ~ .)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但是,我还想指出其他一些事情.你不应该meltedLikert$scoreaes()通话中使用; 你应该只引用数据框中传递的东西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 ~ .)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

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

在此输入图像描述

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

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

在此输入图像描述