Adding percentage labels on pie chart in R

前端 未结 5 1371
渐次进展
渐次进展 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 19:57

    I agree with @hrbrmstr a waffle chart would be better. But to answer the original question... your problem comes from the order in which the wedges are drawn, which will default to alphabetical. As you calculate where to place the labels based on the ordering in your data frame, this works out wrong.

    As a general principle of readability, do all the fancy calculations of labels and positions they go before the actual code drawing the graphic.

    library(dplyr)
    library(ggplot2)
    library(ggmap) # for theme_nothing
    df <- data.frame(value = c(52, 239, 9),
                     Group = c("Positive", "Negative", "Neutral")) %>%
       # factor levels need to be the opposite order of the cumulative sum of the values
       mutate(Group = factor(Group, levels = c("Neutral", "Negative", "Positive")),
              cumulative = cumsum(value),
              midpoint = cumulative - value / 2,
              label = paste0(Group, " ", round(value / sum(value) * 100, 1), "%"))
    
    ggplot(df, aes(x = 1, weight = value, fill = Group)) +
       geom_bar(width = 1, position = "stack") +
       coord_polar(theta = "y") +
       geom_text(aes(x = 1.3, y = midpoint, label = label)) +
       theme_nothing()               
    

提交回复
热议问题