library(tidycensus)
library(tidyverse)
library(sf)
library(ggplot2)
v15_Profile <- load_variables(2015 , "acs5/profile", cache = TRUE) #demographic profile tables

View(v15_Profile)

#Search for variables by keywords in the label 
# v15_Profile[grep(x = v15_Profile$label, "POVERTY"), c("name", "label")]
# v15_Profile[grep(x = v15_Profile$label, "Built 2000 to 2009"), c("name", "label")]

Extract from ACS summary file data

sa_acs<-get_acs(geography = "tract",
                state="TX",
                county = c("Bexar"),
                year = 2017,
                variables=c( "DP05_0001E", 
                            "DP03_0062E") ,
                geometry = T, output = "wide")

#create a county FIPS code - 5 digit
sa_acs$county<-substr(sa_acs$GEOID, 1, 5)

#rename variables and filter missing cases
sa_acs2<-sa_acs%>%
  mutate(totpop= DP05_0001E, medianhi=DP03_0062E) %>%
#  st_transform(crs = 102740)%>%
  na.omit()

Write data out to shapefile

#change the directory
sf::st_write(sa_acs2,dsn="C:/Users/sarah/Documents",layer="sa_tract_dp03_R", driver="ESRI Shapefile", delete_layer=T, update=T)

Mapping of median household income

library(classInt)
library(patchwork)
library(dplyr)

medianhi_map<-sa_acs2 %>%
  mutate(jmedianhi = cut(medianhi,breaks=data.frame(classIntervals(var=sa_acs2$medianhi, n=5, style="pretty")[2])[,1], include.lowest = T))

library(ggsn)

# p1<-ggplot(medianhi_map, aes(fill = cmedianhi, color = cmedianhi)) + 
#   geom_sf() + 
#   ggtitle("Percent Estimate for the Median Household Income", 
#           subtitle = "Bexar County Texas, 2017 - Quantile Breaks")+
#     scale_fill_brewer(palette = "Reds") + 
#   scale_color_brewer(palette = "Reds")+
#   theme(axis.text.x = element_blank(), axis.text.y = element_blank())+
#   north(medianhi_map)+
#   scalebar(medianhi_map, location="bottomleft", dist=5, transform = T,dist_unit = "km",  model="WGS84", st.size =2 )
# p1

p2<-ggplot(medianhi_map, aes(fill = jmedianhi, color = jmedianhi)) + 
  geom_sf() + 
  ggtitle("Percent Estimate for the Median Household Income", 
          subtitle = "Bexar County Texas, 2017 - Pretty Breaks")+
  scale_fill_brewer(palette = "Oranges") + 
  scale_color_brewer(palette = "Oranges")+
    theme(axis.text.x = element_blank(), axis.text.y = element_blank())+
  north(medianhi_map)+
  scalebar(medianhi_map, location="bottomleft", dist=5, transform = T,dist_unit = "km",  model="WGS84", st.size =2)
p2

#ggsave(filename="C:/Users/sarah/Google Drive/MSc Demography/Spring 2020/GIS 5093/gis_class/Homework 1/lab1map1.png")

Interactive map with mapview

library(mapview)
library(RColorBrewer)
pal <- colorRampPalette(brewer.pal(6, "Oranges")) #set colors
mapview(medianhi_map["jmedianhi"], col.regions=pal, legend=T,map.types="OpenStreetMap", layer.name="% African American")