8

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

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 ~ .)

在此处输入图像描述

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

4

1 回答 1

18

根据链接问题中的答案,将值添加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 ~ .)

在此处输入图像描述

但是,我还想指出其他一些事情。你不应该meltedLikert$scoreaes()通话中使用;您应该只引用作为data. 此外,meltedLikert已经是 a 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 ~ .)

在此处输入图像描述

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

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 ~ .)

在此处输入图像描述

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

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 ~ .)

在此处输入图像描述

于 2013-08-29T20:20:38.570 回答