【问题标题】:ggplot labels on bargraph position条形图位置上的ggplot标签
【发布时间】:2016-08-16 02:38:13
【问题描述】:

如果这是一个重复的问题,我真的很抱歉。但由于某种原因,之前给出的答案对我不起作用。 我有以下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,但位置从未改变......我做错了什么?

提前谢谢你!!!

【问题讨论】:

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


    【解决方案1】:

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

    How to use vjust and hjust

    我想您希望每个条都有一个标签,请在 geom_text(aes()) 中使用 group = Taxa

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

    【讨论】:

    • 非常感谢!它在这个示例 df 上效果很好。现在我必须让它在真正的交易中发挥作用......
    • 完成。感谢您提供快速而有帮助的答案。
    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 2016-11-17
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多