Adding percentage labels on pie chart in R

前端 未结 5 1382
渐次进展
渐次进展 2020-12-03 19:23

My data frame looks like

df
   Group   value
1 Positive    52
2 Negative   239
3 Neutral     9

I would like to make a pie chart of the dat

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 20:14

    Here is an idea matching the order of groups in the pie chart and the order of labels. I sorted the data in descending order by value. I also calculated the percentage in advance. When I drew the ggplot figure, I specified the order of Group in the order in mydf (i.e., Negative, Positive, and Neutral) using fct_inorder(). When geom_label_repel() added labels to the pie, the order of label was identical to that of the pie.

    library(dplyr)
    library(ggplot2)
    library(ggrepel)
    library(forcats)
    library(scales)
    
    mydf %>%
    arrange(desc(value)) %>%
    mutate(prop = percent(value / sum(value))) -> mydf 
    
    pie <- ggplot(mydf, aes(x = "", y = value, fill = fct_inorder(Group))) +
           geom_bar(width = 1, stat = "identity") +
           coord_polar("y", start = 0) +
           geom_label_repel(aes(label = prop), size=5, show.legend = F, nudge_x = 1) +
           guides(fill = guide_legend(title = "Group"))
    

    DATA

    mydf <- structure(list(Group = structure(c(3L, 1L, 2L), .Label = c("Negative", 
    "Neutral", "Positive"), class = "factor"), value = c(52L, 239L, 
    9L)), .Names = c("Group", "value"), class = "data.frame", row.names = c("1", 
    "2", "3"))
    

提交回复
热议问题