Add percentage labels to a stacked barplot

前端 未结 2 899
逝去的感伤
逝去的感伤 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 13:59

    This would give you the asnwer:

    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) +
      geom_text(aes(label = paste0(value*100,"%")), 
                position = position_stack(vjust = 0.5), size = 2)
    

    Plot would look like this:

    enter image description here

    0 讨论(0)
  • 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)
    

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