条形图位置上的ggplot标签

时间:2016-04-22 12:46:29

标签: r ggplot2 label geom-bar geom-text

如果这是一个重复的问题,我真的很抱歉。但出于某种原因,先前给出的答案对我不起作用。 我有以下df:

Country<-c("Chile", "Chile", "Finland","Finland")
Taxa<-c("Mammalia","Amphibia","Mammalia","Amphibia")
Loss<-c(0.15, 1, 0.2, 0.75)
df<-data.frame(Country, Taxa, Loss)

我希望将其显示为排名并添加标签。这就是我得到的:

ggplot(df,aes(x=reorder(Country, Loss), y=Loss)) + 
  geom_bar(aes(fill = Taxa), position="dodge", stat="identity") +
  labs(x = "", y = "")+
  ylim(0,1)+
  theme (legend.position="top", legend.title = element_blank(),legend.text = element_text(size = 17),
         axis.text.x  = element_text(size=17), 
         axis.text.y  = element_text(size=17), axis.title.y=element_text(size=17))+
  geom_text(aes(label = Loss), position=position_dodge(width=1))+
  coord_flip()

工作正常!只有我不能像我想要的那样定位标签。我更喜欢标签旁边的标签。我尝试使用width以及一些vjusthjust,但这个位置从未改变过......我做错了什么?

提前谢谢!!!

2 个答案:

答案 0 :(得分:2)

来自?geom_text的想法:

ggplot(df, aes(x=reorder(Country, Loss), y=Loss, label = Loss, fill = Taxa)) + 
  geom_bar(position="dodge", stat="identity") +
  geom_text(aes(y = Loss + 0.02), position = position_dodge(0.9), vjust = 0) + 
  coord_flip()

enter image description here

答案 1 :(得分:2)

正如您所提到的,使用vjusthjust的另一种解决方案。

How to use vjust and hjust

我想您需要每个条形码标签,在group = Taxa中使用geom_text(aes())

enter image description here

ggplot(df,aes(x=reorder(Country, Loss), y=Loss)) +   
geom_bar(aes(fill = Taxa), position="dodge", stat="identity") + 
labs(x = "", y = "")+  ylim(0,1)+  theme (legend.position="top", 
legend.title = element_blank(),legend.text = element_text(size = 17),
axis.text.x  = element_text(size=17), axis.text.y  = element_text(size=17), 
axis.title.y=element_text(size=17))+ 
geom_text(aes(x = reorder(Country, Loss), label = Loss, group = Taxa), 
position=position_dodge(width=1), hjust = -1) 
+  coord_flip()