Add percentage labels to a stacked barplot

前端 未结 2 914
逝去的感伤
逝去的感伤 2020-11-30 13:36

I have successfully made a stacked barplot in R where the percentages add up to 100% for several different categories. I made an example dataframe here.

exam         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 14:01

    You could do something like this...

    #set positions for labels
    example.melt$labelpos <- ifelse(example.melt$variable=="percent.bad",
                             example.melt$value/2, 1 - example.melt$value/2)
    ggplot(example.melt, aes(x=example.Category, y=value, fill = variable)) +
      geom_bar(position = "fill", stat = "identity",color='black',width=0.9) +
      scale_y_continuous(labels = scales::percent) +
    #use positions to plot labels
      geom_text(aes(label = paste0(100*value,"%"),y=labelpos),size = 3)
    

提交回复
热议问题