How to display value in a stacked bar chart by using geom_text?

后端 未结 2 1415
闹比i
闹比i 2021-01-03 08:08

I would like to display the percentage figures in the stacked bar. However, one group has a really low percentage. Two values are overlapping each other. I change to \'posti

相关标签:
2条回答
  • 2021-01-03 08:47

    one solution is to change the stack bar to a dodge one

    x4.can.bar <- ggplot(data=x4.can.m, aes(x=factor(YearQuarter), y=value,fill=canopy)) + 
                        geom_bar(stat="identity",position = "dodge",ymax=100) +
                 geom_text(aes(label =paste(round(value*100,0),"%",sep=""),ymax=0), 
                           position=position_dodge(width=0.9), vjust=-0.25)
    x4.can.bar
    

    enter image description here

    0 讨论(0)
  • 2021-01-03 09:06

    You need to specify reasonable values for the placement of the labels - if you do this outside the ggplot call, it will be far easier than trying to do so within the call.

    You can do this by taking the midpoint of each stacked component.

    Using plyr and ddply this is a simple as taking the cumulative sum and subtracting half the current value within each YearQuarter

    library(plyr)
    x4.can.m <- ddply(x4.can.m, .(YearQuarter), mutate, csum = cumsum(value)-value/2)
    
    x4.can.bar <- ggplot(data=x4.can.m, aes(x=factor(YearQuarter), y=value,fill=canopy)) +  
     geom_bar(stat="identity",position = "stack",ymax=100)
    
    x4.can.bar + 
     scale_y_continuous(expand = c(0,0), labels = percent) +
     labs(y="Percentage",x="Year Quarter")+
     geom_text(aes(y = csum,label =paste(round(value*100,0),"%",sep="")),
               size = 3, hjust = 1, vjust = 0)
    

    Note that I am using ggplot2_0.9.2.1, so formatter is no longer a valid argument to scale_y_continuous, replaced with label = percent. See this question and related links

    enter image description here

    0 讨论(0)
提交回复
热议问题