# Make graph of overall trends nationally and by region

dir.create('output/trends')

# Bring in national data
natdta = read_csv('intermediate_data/sumstats/sumstats_nat_raceex.csv')

natdta$incsamp = paste(natdta$subpop,natdta$incdef, sep = '_')

ndta = natdta %>% filter(race != 'o', incsamp == 'all_faminc_sqrt') %>% select(med,year,race,incsamp) %>% pivot_wider(id_cols = c(incsamp,year), names_from = race, values_from = med)

ndta$rat_bw_med = ndta$b / ndta$w
ndta$Year = factor(ndta$year, levels = c(1970,1980,1990,2000,2009,2014,2019),
                   labels = c(1969,1979,1989,1999,2007,2012,2017)) %>% as.character() %>% as.numeric()

# Regional data
southdta = read_csv('intermediate_data/sumstats/sumstats_region_raceex.csv')

southdta$incsamp = paste(southdta$subpop,southdta$incdef, sep = '_')

sdta = southdta %>% filter(incsamp == 'all_faminc_sqrt',race != 'o', racedef == 'expansive') %>% distinct(south,race,year, .keep_all = TRUE) %>% select(med,year,race,incsamp,south) %>% pivot_wider(id_cols = c(incsamp,year,south), names_from = race, values_from = med)

# Create ratios
sdta$rat_bw_med = sdta$b / sdta$w
sdta$Year = factor(sdta$year, levels = c(1970,1980,1990,2000,2009,2014,2019),
                   labels = c(1969,1979,1989,1999,2007,2012,2017)) %>% as.character() %>% as.numeric()
sdta$South = factor(sdta$south, levels = c("South",'Rest of country')) %>% as.character()
sdta$comp = 'South vs. rest of country'

# Make one big dataset
ndta$South = 'Entire US'
ndta$comp = 'Entire US'

fdta = bind_rows(ndta, sdta)
fdta$South = factor(fdta$South, levels = c('Entire US','South','Rest of country'))

pdf('output/trends/trends_south.pdf',height = 4,width = 7)
gplt = ggplot(fdta, aes(x = Year, y = rat_bw_med, lty = South)) + 
  geom_line() + 
  geom_point() + 
  geom_hline(yintercept = 1, lty = 2,alpha = .4) +
  geom_hline(yintercept = 0, lty = 1,alpha = .4) +
  scale_linetype(name = 'Region') +
  facet_grid(. ~ comp) +
  scale_y_continuous(limits = c(0,1), name = 'Median Black-white family income ratio\n(aggregate value)', labels = percent) +
  scale_x_continuous(name = 'Year')

print(gplt)
dev.off()


