参见英文答案 >
RE: Alignment of numbers on the individual bars with ggplot21个
我用以下代码创建了这个图:
我用以下代码创建了这个图:
library(ggplot2); library(reshape2); library(plyr) likert <- data.frame(age = c(rep("young",5),rep("middle",rep("old",5)),score1 = c(rep("unlikely",1),rep("likely",rep("very likely",13)),score2 = c(rep("disagree",6),rep("neutral",4),rep("agree",score3 = c(rep("no",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),group=score,label=meltedLikert$score),size=4) + facet_grid(age ~ .)
解决方法
根据
linked question中的答案,将position = position_dodge(width = 0.9)添加到geom_text调用行中的值:
ggplot(meltedLikert[meltedLikert$variable != "age",position = position_dodge(width=0.9),size=4) + facet_grid(age ~ .)
但是,我还想指出其他一些事情.你不应该在aes()电话中使用meltedLikert $得分;你应该只引用数据框中作为数据传递的东西.此外,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 ~ .)
您可以通过将其固定在原始数据中来修复条形的顺序:
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,size=4) + facet_grid(age ~ .)
当然,在这一点上,颜色实际上并没有添加任何东西,因为所有东西都直接在图表上标记,所以我只是完全摆脱它们.
ggplot(tabulatedLikert2,group=score)) + geom_bar(position="dodge",stat="identity",fill="gray70") + geom_text(aes(label=score),size=4) + facet_grid(age ~ .)