Home > Software engineering >  ggplot plotting bars that show the sum of other columns
ggplot plotting bars that show the sum of other columns

Time:12-31

Hello and happy holidays my data looks like:

ID <- c(1,2,3,4)
time_1 <- c(12,20,31,18)
time_2 <- c(5,8,11,7)
time_3 <- c(15,5,9,17)
total_time <- c(32,33,51,42)
data_test<- data.frame(ID,time_1,time_2,time_3,total_time)
data_test %>% glimpse()

$ ID         <dbl> 1, 2, 3, 4
$ time_1     <dbl> 12, 20, 31, 18
$ time_2     <dbl> 5, 8, 11, 7
$ time_3     <dbl> 15, 5, 9, 17
$ total_time <dbl> 32, 33, 51, 42

the variable total_time is the sum of the other time columns. I need to plot total_time with bars for each ID in a way that in each bar I can see the amount of all three time columns in order to see each time column within the total_time bar linked to each ID.

I understand it is an easy problem for most of you folks and I apologize for taking your time. It's just bugging me now.

Thank you and look forward to hearing from you!

CodePudding user response:

You want a stacked bar chart. In ggplot this is easily done in combination with pivot_longer()

data_test %>% pivot_longer(time_1:time_3)  %>%
  ggplot()   
  geom_bar(aes(ID, value, fill=name),position = "stack",stat = "identity" )

enter image description here

  • Related