How to prevent two labels to overlap in a barchart?

后端 未结 4 679
失恋的感觉
失恋的感觉 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 17:56

    Based on Didzis plot you could also increase readability by keeping the position on the y axis constant and by colouring the text in the same colour as the legend.

    library(ggplot2)
    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)
    
    
    library(plyr)
    text.df<-ddply(dat,.(Week,Status),function(x) data.frame(count=nrow(x)))
    text.df$ypos[text.df$Status=="Not-Shipped"]<- -15
    text.df$ypos[text.df$Status=="Shipped"]<- -55
    
    p <- ggplot(dat,aes(as.factor(Week),fill=Status))+geom_bar()+
    geom_text(data=text.df,aes(x=as.factor(Week),y=ypos,label=count),colour=ifelse(text.df$Status=="Not-Shipped","#F8766D","#00BFC4"))
    

    enter image description here

提交回复
热议问题