Home > Enterprise >  ggplot percentage within grouping
ggplot percentage within grouping

Time:10-23

How would I be able to plot the grouped percentages (not the counts) of a dataset in ggplot? For example this plot

library(survival)
    ggplot(data=kidney, aes(disease)) 
      geom_bar(aes(fill=as.factor(sex)), position="dodge") 

How could I plot the sex as a percentage of the disease group that they are in such that each disease group should add up to 100%?

CodePudding user response:

You can calculate the percentage first and then plot the data.

library(survival)
library(dplyr)
library(ggplot2)

kidney %>%
  count(disease, sex = factor(sex))  %>%
  group_by(disease) %>%
  mutate(n = prop.table(n) * 100) %>%
  ggplot(aes(disease, n, fill = sex))   geom_col(position = 'dodge')

enter image description here

  • Related