Display percentage by column on a stacked bar graph

前端 未结 2 953
耶瑟儿~
耶瑟儿~ 2021-01-19 06:54

I\'m trying to plot a stacked bar chart showing the relative percentages of each group within a column.

Here\'s an illustration of my problem, using the default mpg

2条回答
  •  轮回少年
    2021-01-19 07:18

    If I compare your question to the link you gave than the difference is that the link "counted" them selves. That's what I did. I'am nor sure if this is than suitable for your real data.

    library(ggplot2)
    library(dplyr)
    
    mpg %>%
      mutate(manufacturer = as.factor(manufacturer),
             class = as.factor(class)) %>%
      group_by(manufacturer, class) %>%
      summarise(count_class = n()) %>%
      group_by(manufacturer) %>%
      mutate(count_man = sum(count_class)) %>%
      mutate(percent = count_class / count_man * 100) %>%
      ggplot() +
      geom_bar(aes(x = manufacturer,
                   y = count_man, 
                   group = class,
                   fill = class), 
               stat = "identity") +
      geom_text(aes(x = manufacturer,
                    y = count_man,
                    label = sprintf("%0.1f%%", percent)),
                position = position_stack(vjust = 0.5))
    

    Edit, based on comment :

    I made a mistake by selecting the wrong column for y

    library(ggplot2)
    library(dplyr)
    
    mpg %>%
      mutate(manufacturer = as.factor(manufacturer),
             class = as.factor(class)) %>%
      group_by(manufacturer, class) %>%
      summarise(count_class = n()) %>%
      group_by(manufacturer) %>%
      mutate(count_man = sum(count_class)) %>%
      mutate(percent = count_class / count_man * 100) %>%
      ungroup() %>%
      ggplot(aes(x = manufacturer,
                 y = count_class,
                 group = class)) +
      geom_bar(aes(fill = class), 
               stat = "identity") +
      geom_text(aes(label = sprintf("%0.1f%%", percent)),
                position = position_stack(vjust = 0.5))
    

提交回复
热议问题