0
votes

My data set would be somewhat like;

       Gender Age Count
1   female 35     1
2   male  34     2
3   male  35     1
4   male  37     2
5   female  34     2

I want Age as my X axis and for Y axis it should show the count of male and Female as in stacked bar plot.

Can someone please help me here. Thank you

1
Can you show what you have tried so far? - Chris
Have you tried searching the internet or SO? Have you seen this? cookbook-r.com/Graphs/Bar_and_line_graphs_(ggplot2) - Roman Luštrik

1 Answers

0
votes
# Load package
# package ggplot2 and dplyr are part of the tidyverse package
library(tidyverse)

# Create example data frame
dt <- read.csv(text = "Gender, Age, Count
female, 35, 1
male, 34, 2
male, 35, 1
male, 37, 2
female, 34, 2")

# Process the data frame, calcualte the total count of each gender and age combination
dt2 <- dt %>%
  group_by(Age, Gender) %>%
  summarise(Count = sum(Count))

# Plot the data use geom_bar, set stat = "identity"
ggplot(dt2, aes(x = Age, y = Count, fill = Gender)) +
  geom_bar(stat = "identity")

# Or you can use geom_col, which is the same
ggplot(dt2, aes(x = Age, y = Count, fill = Gender)) +
  geom_col()