0

I have a data frame with 1800 rows and 2 columns, riskGrp ("1", "2", '3") and mortality (0, 1). What I'd like is a bar chart that shows % mortality by riskGrp. I tried the following, but only got the % mortality that each risk group contributes. Here's my code:

library(tidyverse)

v1 <- data.frame(
  riskGrp = c("Low", "Low", "Low", "Mid", "Mid", "High", "High", "High", "High"), 
  mortality = c(0, 0, 1, 0, 1, 0, 1, 1, 1) 
)

ggplot(v1, aes(riskGrp)) + 
  geom_bar(aes( y=mortality/sum(mortality)), stat = "identity") +
  labs(fill = "ICU Disposition", x="Risk Group") +
  scale_y_continuous(labels = scales::percent)

The graph should have three bars: "Low" with a mortality = 33%, "Mid" with a mortality of 50%, and "High" with a mortality of 75%. How can I get stratified mortality rates?

Thanks!

Andrew


O.K., here's a minimum reproducible example:

library(tidyverse)

v1 <- data.frame(
  riskGrp = c("Low", "Low", "Low", "Mid", "Mid", "High", "High", "High", "High"), 
  mortality = c(0, 0, 1, 0, 1, 0, 1, 1, 1) 
)

ggplot(v1, aes(riskGrp)) + 
  geom_bar(aes( y=mortality/sum(mortality)), stat = "identity") +
  labs(fill = "ICU Disposition", x="Risk Group") +
  scale_y_continuous(labels = scales::percent)

The graph should have three bars: "Low" with a mortality = 33%, "Mid" with a mortality of 50%, and "High" with a mortality of 75%.

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
Andrew K.
  • 21
  • 2
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Apr 01 '21 at 19:10

1 Answers1

0

I would just aggregate the data beforehand and then plot using geom_col:

library(tidyverse)

v1 %>%
    group_by(riskGrp) %>%
    summarise(mortality = mean(mortality)) %>%
    ggplot(aes(riskGrp, mortality))+geom_col()+
    scale_x_discrete(limits = c("Low", "Mid", "High"))+
    scale_y_continuous(labels = scales::percent)

enter image description here

bouncyball
  • 10,631
  • 19
  • 31