-2

If this is my dataset.

   Surgery   Surv_Prob            Group
   CV          0.5113        Diabetic
   Hip         0.6619        Diabetic
   Knee        0.6665        Diabetic
   QFox        0.7054        Diabetic

   CV          0.5113    Non-Diabetic
   Hip         0.6629    Non-Diabetic
   Knee        0.6744    Non-Diabetic
   QFox        0.7073    Non-Diabetic

How do i plot a stacked bar plot like this below.

enter image description here

Please note the values are already cumulative in nature, so the plot should show a very little increase from CV to Hip (delta = 0.6619- 0.5113)

And the order should be CV -> Hip -> Knee -> QFox

King Frazier
  • 243
  • 3
  • 14

1 Answers1

2

There could be a way where you can plot the cumulative values directly, however one way is to get the actual value and plot the stacked bar plot by arranging the Surgery data in the order you want using factor. For factor levels I have used rev(unique(Surgery)) for convenience as you want order in opposite order of how they appear in the dataset. For more complex types you might need to add levels manually.

library(tidyverse)

df %>%
  group_by(Group) %>%
  mutate(Surv_Prob1 = c(Surv_Prob[1], diff(Surv_Prob)), 
         Surgery = factor(Surgery, levels = rev(unique(Surgery)))) %>%
  ggplot() + aes(Group, Surv_Prob1, fill = Surgery, label = Surv_Prob) +
  geom_bar(stat = "identity") + 
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

data

df <- structure(list(Surgery = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 
3L, 4L), .Label = c("CV", "Hip", "Knee", "QFox"), class = "factor"), 
Surv_Prob = c(0.5113, 0.6619, 0.6665, 0.7054, 0.5113, 0.6629, 
0.6744, 0.7073), Group = structure(c(1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L), .Label = c("Diabetic", "Non-Diabetic"), class = 
"factor")), class = "data.frame", row.names = c(NA, -8L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213