representation of two bars for each range in R

Viewed 35

I have been trying to make a bar-chart but I am pretty stuck at the data modeling and presentation of it. Code is below. the fixedTable is a data frame which I take data from him,and the logic vector is the columns that I need from my data set(here there is no problem).

in this link there is an example of the wanted plot. but instead of china and Italy there should be 0 and 1. for example: in the age group of 50-59 there are 49 survived(1) and 40 not survived(0).hence,the range of this group needs to include the two bars:1 with height of 49 and 0 with height of 40.

code:

ageAndSurvived<-subset(fixedTable,select = logicVector)

x<-split(ageAndSurvived,cut(ageAndSurvived$Age,seq(0,100,by=10))) #tried this but didnt help much

head(ageAndSurvived)
##   Survived Age
## 1        0  22
## 2        1  38
## 3        1  26
## 4        1  35
## 5        0  35
## 7        0  54

for example:in the third row there is a person who survived and his age is 26.

I would be glad for a way how to do it. prefer with base R. thank you very much in advance! :)

1 Answers

First, I create a group for the age ranges, then change the levels to names, so that we can use those to plot. Then, I use the age group for the x-axis and use count in stat for the y-axis, then need to put the groups (i.e., 0 and 1) as a factor.

library(tidyverse)

results <-  group_by(df, agegrp = cut(Age, c(seq(9, 79, 10))), Survived)
levels(results$agegrp) <- c("0-9", "10-19", "20-29", "30-39", "40-49", "50-59", "60-69", "70-79", "80+")

results %>%
  ggplot(aes(x = agegrp, fill = as.factor(Survived))) +
  geom_bar(position="dodge", stat="count")

Output

enter image description here

Data

df <- structure(list(Survived = c(0L, 1L, 1L, 1L, 0L, 0L, 1L, 1L, 1L, 
1L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 
1L, 0L, 1L, 0L, 1L), Age = c(22L, 38L, 26L, 35L, 35L, 54L, 22L, 
38L, 26L, 35L, 35L, 54L, 22L, 38L, 26L, 35L, 35L, 54L, 22L, 38L, 
26L, 35L, 35L, 54L, 22L, 38L, 26L, 35L, 35L, 54L)), row.names = c("1", 
"2", "3", "4", "5", "7", "11", "21", "31", "41", "51", "71", 
"12", "22", "32", "42", "52", "72", "13", "23", "33", "43", "53", 
"73", "14", "24", "34", "44", "54", "74"), class = "data.frame")
Related