How to prevent two labels to overlap in a barchart?

后端 未结 4 690
失恋的感觉
失恋的感觉 2020-12-31 17:37

The image below shows a chart that I created with the code below. I highlighted the missing or overlapping labels. Is there a way to tell ggplot2 to not overlap labels?

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-31 18:09

    Made new sample data (inspired by code of @agstudy).

    week <- sample(0:5,1000,rep=TRUE,prob=c(0.2,0.05,0.15,0.5,0.03,0.1))
    statuses <- gl(2,1000,labels=c('Not-Shipped', 'Shipped'))
    dat <- data.frame(Week = week, Status = statuses)
    

    Using function ddply() from library plyr made new data frame text.df for labels. Column count contains number of observations in each combination of Week and Status. Then added column ypos that contains cumulative sum of count for each Week plus 15. This will be used for y position. For Not-Shipped ypos replaced with -10.

    library(plyr)
    text.df<-ddply(dat,.(Week,Status),function(x) data.frame(count=nrow(x)))
    text.df<-ddply(text.df,.(Week),transform,ypos=cumsum(count)+15)
    text.df$ypos[text.df$Status=="Not-Shipped"]<- -10
    

    Now labels are plotted with geom_text() using new data frame.

    ggplot(dat,aes(as.factor(Week),fill=Status))+geom_bar()+
      geom_text(data=text.df,aes(x=as.factor(Week),y=ypos,label=count))
    

    enter image description here

提交回复
热议问题