Skip to content

Instantly share code, notes, and snippets.

@r-conway
Created October 10, 2016 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r-conway/1aca00055005ab8016cd4ace9b6ab178 to your computer and use it in GitHub Desktop.
Save r-conway/1aca00055005ab8016cd4ace9b6ab178 to your computer and use it in GitHub Desktop.
#load packages
library(readr)
library(dplyr)
library(ggplot2)
library(RColorBrewer)
#REad in data
a <- read_csv('./data/usa_00006.csv')
#filter so we're only taking from german, austira, and hungary, both first and second generation
a2<-a%>%filter(BPL==453 | BPL==454 | BPL==450 | MBPL==453 | MBPL==454 | MBPL== 450 | FBPL==453 | FBPL==454 | FBPL==450)
#Assign sex
b<-a2 %>% mutate(Sex=factor(SEX, labels=c('Male','Female')))
#Create age groupings
c<-b %>% mutate(Age=ifelse(AGE>=80,8, floor(AGE/10)))
#label age groupings
d<-c %>% mutate(Age=factor(Age,labels=c('0-9','10-19','20-29','30-39','40-49','50-59','60-69','70-79','80+')))
#OR
#agecates<-'0-9'
#for(i in1:7) {
#agecats<-c(agecats,paste(i,'0-',i,0,sep' '))
#}
#Split into first and second generation
e<-d %>% mutate(Gen=ifelse(BPL==453 |BPL==454 | BPL==450,'First Generation',
ifelse(BPL<=150, 'Second Generation', 'Neither')))
#Remove alaska and Hawaii
f<-e%>%filter(YEAR>=1960 | !(STATEFIP %in% c(2,15)))
#Remove those who aren't first or second gen
f2<-f%>%filter(Gen != 'Neither')
#Ensure were using 'SLWT' or "PERWT' Correctly
g<-f2%>% mutate(Weight=ifelse(YEAR==1940 & Gen=='Second Generation',SLWT,PERWT))
#Sum data for catagories
h<-g%>%group_by(Age,Sex,Gen,YEAR) %>% summarise(Number=sum(Weight))
#Negate mens data so it goes to left of axis
h2=h%>% mutate(Number=ifelse(Sex=='Male',-1*Number,Number))
ggplot(data=h2,aes(x=Age,y=Number,fill=Sex)) +
geom_bar(data=h2[h2$Sex=='Male',],stat='identity') +
geom_bar(data=h2[h2$Sex=='Female',],stat='identity') +
coord_flip() +
facet_grid(Gen~.~YEAR) +
scale_y_continuous(breaks=c(-600000,-300000,0,300000,600000),
labels=c('600','300','0','300','600')
)+
labs(y='Population in Thousands',title='Population Pyramids for Immigrants and their Children') +
scale_fill_brewer(palette='Set1',guide=guide_legend(reverse=TRUE)) +
theme(legend.position='bottom')+
theme_bw()
ggsave("10.6.pdf", width=10, height=7.5)
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment