0
votes

I am trying to construct a bar plot with percentage on the y axis. I have some data in table format and want to plot it into bar plot

library(survival)

kidney$mortality <- ifelse(kidney$status==1, "Dead", "Alive")

table1(~ disease
       | mortality * sex, data=kidney )

I am trying to assess the probability of people who died in each disease category and the numbered category like this

  1. For all the people in category 1 and disease other (6 total) divided by the number of dead 1s in the other disease category (6 total) with a bar at 100 percent because 6/6.

There will be a total of 8 bars in this case.

How would I work this into a solid ggplot barplot with the percent on the y axis?

1

1 Answers

1
votes

Libraries

library(tidyverse)
library(survival)

Code

kidney %>% 
  #Change status from 0/1 to Dead/Alive
  mutate(status = if_else(status==1, "Dead", "Alive")) %>% 
  #Count number of observations for each combination of sex, status and disease
  count(disease,status,sex) %>%
  #Grouping by next calculation by disease and sex
  group_by(disease,sex) %>% 
  mutate(
    #Total observations for each disease and sex
    N = sum(n),
    #Percentage of status by disease and sex
    p = 100*n/N
  ) %>% 
  #Filter only the dead
  filter(status == "Dead") %>% 
  ggplot(aes(x = disease, y = p, fill = as.factor(sex)))+
  # Adding column geometry
  geom_col(position = position_dodge())+
  # Adding text in the top of the columns
  geom_text(aes(label = round(p)),position = position_dodge(1), vjust = 2)

Output

enter image description here