Alternate geom_text position with hjust

前端 未结 1 1457
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 15:39

I\'m plotting a stacked bar graph and use geom_text to insert the value of each stack. The difficulty I\'m facing is that some stacks are very small/narrow, so

相关标签:
1条回答
  • 2020-12-31 16:17

    By creating a hjust variable, you can achieve the desired result. The code:

    mydf$hj <- rep(c(1,0,-1), length.out=27)
    
    ggplot(mydf, aes(x=variable, y=value, fill=Category)) + 
      geom_bar(stat="identity") +
      geom_text(aes(label=value, y=pos-(value/2), hjust=hj), size=4)
    

    which gives: enter image description here


    A slightly alternative solution proposed by @konvas:

    ggplot(mydf, aes(x=variable, y=value, fill=Category)) + 
      geom_bar(stat="identity") +
      geom_text(aes(label=value, y=pos-(value/2), hjust=rep(c(1,0,-1), length.out=length(value))), size=4)
    
    0 讨论(0)
提交回复
热议问题