rj44
rj44

Reputation: 305

ggplot percentage within grouping

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%?

Upvotes: 0

Views: 1684

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

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

Upvotes: 2

Related Questions