通过填充位置向geom_bar添加标签

时间:2016-12-09 05:23:34

标签: r ggplot2 geom-bar

我有以下数据:

set.seed(1)
df <- data.frame(type=c("A","B","D","A","C","D","B","C","D","E"),
                 count=as.integer(runif(10,100,200)),
                 sample=c(1,1,1,2,2,2,3,3,3,3),stringsAsFactors=F)
df$type <- factor(df$type,levels=unique(sort(df$type)))

我使用geom_bar绘图:

require(ggplot2)
ggplot(df,aes(x=sample,y=count,fill=type))+geom_bar(stat="identity",position="dodge")+theme(legend.position="none")

enter image description here

我的问题是如何在每个栏顶部添加df$type作为标签?

添加:

geom_text(aes(label=type,hjust=0),position=("dodge"))

显然不起作用

1 个答案:

答案 0 :(得分:1)

这将有效:

ggplot(df,aes(x=sample,y=count,fill=type))+
  geom_bar(stat="identity",position="dodge")+
  geom_text(aes(label=type,hjust=0, vjust=-0.1),position=position_dodge(width = 1))+
  theme(legend.position="none") 

enter image description here