【问题标题】:Add labels to geom_bar by fill location通过填充位置将标签添加到 geom_bar
【发布时间】:2017-04-24 12:43:29
【问题描述】:

我有以下数据:

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")

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

添加:

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

显然不行

【问题讨论】:

标签: r ggplot2 geom-bar


【解决方案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") 

【讨论】:

  • 谢谢。我玩过 hjust 但无法让标签相对于它们的条居中(hjust=0.5 接近但还不够)。有什么想法吗?
  • @dan 您可以同时更改宽度和 hjust 以将文本放置到您想要的位置。
  • 要将标签居中,使用width = 0.9 并删除hjust = 0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 2017-11-02
  • 1970-01-01
  • 1970-01-01
  • 2018-03-05
  • 2021-07-24
相关资源
最近更新 更多