Search code examples
rggplot2grouped-bar-chart

grouped bar chart with age range within each group


I have a list of people and their group and age in a table similar to the example below. I would like to draw a grouped bar chart based on age range.

  Group Age
1  G1    29
2  G2    25
3  G3    55
4  G2    33
5  G1    70
6  G3    80

I tried the following syntax given here, but not sure how to divide the plots into three groups and age ranges within each group

df<- mutate(df, age_class = cut(Age, breaks = seq(20, 80, by = 10)))  
ggplot(df) + geom_bar(aes(x = age_class, fill = Group), position = "dodge") + scale_fill_manual(values = c("red", "blue", "green"))

Solution

  • Assuming you want a bar plot that counts the number of times each group appears in each age range (correct me if not, but this is what your attempt tried), you can do the following:

    library(tidyverse)
    # Reproducing your data
    df1 <- tibble(
      Group = c("G1", "G2", "G3", "G1", "G2", "G3"),
      Age = c(29, 25, 55, 33, 70, 80)
    )
    

    One of the problems with your current attempt is that you're trying to direct cut towards a column called weight, but there is no such column present in your data. To fix this, you can correctly refer to your column Age as below:

    df1 <- df1 %>% mutate(Age_class = cut(Age, breaks = seq(20, 80, by = 10))) 
    

    Then, plot like so:

    ggplot(df1, aes(x = Age_class, fill = Group)) + 
      geom_bar(position = "dodge") + 
      scale_fill_manual(values = c("red", "blue", "green"))
    

    This gives the count of each age range within each group - all the counts are 1 in your reproducible example, so the output graph looks like this:

    ggplot bar chart of count in each group, per age class