ggplot条形图上的标签位置

3

非常抱歉,如果这是一个重复的问题。但出于某种原因,以前给出的答案对我没有用。

我有以下数据框:

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个回答

4

灵感来自于 ?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


4

你提到了使用vjusthjust的另一种解决方案。

如何使用vjusthjust

我认为您想要每个柱子一个标签,请在geom_text(aes())中使用group = Taxa

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

非常感谢!它在这个样本数据框上运行得很好。现在我必须让它在真实的数据上运行... - samyandi
完成。谢谢你快速和有帮助的回答。 - samyandi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接