1

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"))
tdy
  • 36,675
  • 19
  • 86
  • 83
BeginneR
  • 69
  • 7

1 Answers1

1

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

Rory S
  • 1,278
  • 5
  • 17
  • Thanks !! I am just wondering what changes need to be done if I want my x-axis to have three separate groups i.e. G1, G2, and G3 and within each group, there are ranges (i.e 20-30, 30-40 rtc.) as you plotted. – BeginneR Aug 04 '21 at 13:55
  • I think I got it now. This works for me `ggplot(df1, aes(x = Group, fill = age_class)) + geom_bar(position = "dodge") + scale_fill_manual(values = c("red", "blue", "green", "orange", "yellow"))` – BeginneR Aug 04 '21 at 15:39
  • @BeginneR great, that's what I'd have suggested - no worries! – Rory S Aug 04 '21 at 15:59
  • Thanks a lot !! I am just trying for the percentage (instead of count) of each range within each group. Is there any fix to this? – BeginneR Aug 04 '21 at 16:13
  • @BeginneR you'd probably have to calculate the proportion of "Group" occurences within each `Age_class` using `mutate`, and then plot this on the y axis of your graph. Perhaps you could post a new question asking this, so that the answer is more visible? I'm happy to give it a go. – Rory S Aug 05 '21 at 06:46