stacked bar chart 12

Hi
I'm kind of new in R, so i'm sorry if it is to basically a question.
I am trying to do a stacked bar chart and feel kind of lost in it.
I have 260 persons in four different groups each person with a variable, "mm". The groups are in the data defined by the same column, "tid" by a number (1-4).
Example:


I want to do the stacked bar chart by grouping each group (1-4) into "skinny", "normal" and "big". Furthermore each group has different definitions of skinny, normal and big:
Group 1: Skinny = mm < 14, normal = mm = 14-16 & big = mm > 16.
Group 2: Skinny = mm < 16, normal = mm = 16-19 & big = mm > 19.
Group 3: Skinny = mm < 15, normal = mm = 15-18 & big = mm > 18.
Group 4: Skinny = mm < 13, normal = mm = 13-16 & big = mm > 16.

It that even possible? :slight_smile:
Thank you very much.
Best Regards Kasper

library(tidyverse)

#example data
(exampldf <- tibble(
  tid = rep(1:4,65),
  mm = rnorm(260,16,4)
))

#helper function to classify into types
catfunc <- function(a,b,m){
  case_when(m < a ~ 'skinny',
                     m < b ~ 'normal',
                     TRUE ~ 'big')
}

#classify
(exampldf2 <- mutate(exampldf,
                     g = case_when(tid==1 ~ catfunc(14,16,mm),
                                   tid==2 ~ catfunc(16,19,mm),
                                   tid==3 ~ catfunc(15,18,mm),
                                   tid==4 ~ catfunc(13,16,mm)
                     ))
)

#plot
ggplot(data=exampldf2,
       mapping=aes(x=tid,fill=g)) + 
  geom_bar()

I changed your "exampldf" to my own dataset and it worked! Thank you so much! :smiley:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.