Created
October 10, 2016 04:44
-
-
Save helenaeitel/3b007163c22c1e8f822f839f13552db7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Helena Eitel | |
#Professor Merchant | |
#QSS 30.05 | |
#Lab Assignment 4: Population Pyramids | |
library(readr) | |
library(dplyr) | |
library(ggplot2) | |
library(RColorBrewer) | |
a <- read_csv('./Extract 4.csv') | |
#recode the sex variable | |
b <- a %>% mutate(Sex=factor(SEX,labels=c('Male','Female'))) | |
#create age variable | |
c <- b %>% mutate(Age=ifelse(AGE>=80,8,floor(AGE/10))) | |
#create vector of labels for age factor variable | |
agecats <- '0-9' | |
for (i in 1:7) { | |
agecats <- c(agecats,paste(i,'0-',i,9,sep='')) | |
} | |
agecats <- c(agecats,'80+') | |
d <- c %>% mutate(Age=factor(Age,labels=agecats)) | |
#add the generation variable 'Gen' | |
e <- d %>% mutate(Gen=ifelse(BPL %in% c(430:440),'First Generation', | |
ifelse(MBPL %in% c(430:440) | FBPL %in% c(430:440),'Second Generation','Neither'))) | |
#don't include Alaska or Hawaii until 1960 | |
f <- e %>% filter(YEAR>= 1960 | !(STATEFIP %in% c(2,15))) | |
#remove anyone who is neither first or second generation | |
g <- f %>% filter(Gen!='Neither') | |
h <- g %>% mutate(weight=ifelse(YEAR==1940 & Gen=='Second Generation',SLWT,PERWT)) | |
i <- h %>% group_by(Age,Sex,Gen,YEAR) %>% summarise(Number=sum(weight)) | |
#make all of the male numbers negative so that they move left from the center of the axis | |
j <- i %>% mutate(Number=ifelse(Sex=='Female',Number*-1,Number)) | |
#create the population pyramid graph | |
#create a bargraph that you then flip on its side | |
png('PopulationPyramid1.png',height=500,width=2000) | |
ggplot(data=j,aes(x=Age,y=Number,fill=Sex)) + | |
geom_bar(data=j[j$Sex=='Male',],stat='identity') + | |
geom_bar(data=j[j$Sex=='Female',],stat='identity') + | |
coord_flip() + | |
facet_grid(Gen~.~YEAR) + | |
scale_y_continuous(breaks=c(-600000,-300000,0,300000,600000),labels=c('6','3','0','3','6')) + | |
labs(y='Population in Hundreds of Thousands',title='Population Pyramids for Immigrants from Southern Europe and Their Children') + | |
scale_fill_brewer(palette='Set1') + | |
guides(fill=guide_legend(title='')) + | |
theme_bw() + theme(legend.position='bottom') | |
dev.off() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment