forked from dlab-berkeley/R-Census-Data-Legacy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
.Rhistory
512 lines (512 loc) · 16.9 KB
/
.Rhistory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
head(pop2010w)
pop2010 <- get_decennial(geography = "state", # census tabulation unit
variables = "P001001", # variable(s) of interest
year = 2010) # census year
head(pop2010)
knitr::opts_chunk$set(echo = TRUE)
# Create a list of the packages we will use
list_of_packages <- c("tidyverse","sf","mapview","tigris", "tidycensus")
list_of_packages
# Create a list of the packages we will use
list_of_packages <- c("tidyverse","sf","mapview","tigris", "tidycensus")
# Identify any new packages that will need to be installed
new_packages <- list_of_packages[!(list_of_packages %in% installed.packages()[,"Package"])]
# Install any packages that are not installed (new_packages)
if(length(new_packages) > 0) {
print(paste("Installing these packages:", new_packages))
install.packages(new_packages)
} else {
print("All packages already installed!")
}
# Identify any new packages that will need to be installed
new_packages <- list_of_packages[!(list_of_packages %in% installed.packages()[,"Package"])]
new_packages
if(length(new_packages) > 0) {
print(paste("Installing these packages:", new_packages))
install.packages(new_packages)
} else {
print("All packages already installed!")
}
library(tidycensus)
library(tidyverse)
#library(tigris)
library(sf)
library(mapview)
sessionInfo()
knitr::opts_chunk$set(echo = TRUE)
# Create a list of the packages we will use
list_of_packages <- c("tidyverse","sf","mapview","tigris", "tidycensus")
# Identify any new packages that will need to be installed
new_packages <- list_of_packages[!(list_of_packages %in% installed.packages()[,"Package"])]
# Install any packages that are not installed (new_packages)
if(length(new_packages) > 0) {
print(paste("Installing these packages:", new_packages))
install.packages(new_packages)
} else {
print("All packages already installed!")
}
sessionInfo()
library(tidycensus)
sessionInfo()
library(tidyverse)
library(sf)
library(mapview)
?census_api_key
# Install your census api key - long alphanumeric string
census_api_key("THE_BIG_LONG_ALPHANUMERIC_API_KEY_YOU_GOT_FROM_CENSUS")
# source (run) an r script that creates a variable with my key
source("../../keys/census_api_key.R")
print(my_census_api_key)
# source (run) an r script that creates a variable with my key
source("../../keys/census_api_key.R")
print(my_census_api_key)
# register the key
census_api_key(key = my_census_api_key)
pop2010 <- get_decennial(geography = "state", # census tabulation unit
variables = "P001001", # variable(s) of interest
year = 2010) # census year
head(pop2010)
# wide format
pop2010w <- get_decennial(geography = "state", # census tabulation unit
variables = "P001001", # variable(s) of interest
year = 2010, # census year
output="wide") # get output in wide format
head(pop2010w)
# wide format
pop2010w <- get_decennial(geography = "state", # census tabulation unit
variables = "P001001", # variable(s) of interest
year = 2010, # census year
output="wide") # get output in wide format
head(pop2010w)
get_decennial(geography = "county", # census tabulation unit
variables = "P001001", # variable(s) of interest
year = 2010, # census year
state='CA') # Filter by state is CA
get_decennial(geography = "county", # census tabulation unit
variables = "P001001", # variable(s) of interest
year = 2010, # census year
state='CA', # Filter by state is CA
county='Alameda') # Filter by county Alameda
pop_plot<- ggplot(data=pop2010, aes(x=reorder(NAME,value), y=value/1000000)) +
geom_bar(stat="identity") + coord_flip() +
theme_minimal() +
labs(title = "2010 US Population by State") +
xlab("State") +
ylab("in millions")
# display the plot
pop_plot
ggplot(data=pop2010, aes(x=reorder(NAME,value), y=value/1000000)) +
geom_point()
ggplot(data=pop2010,
aes(x=value, y=reorder(NAME,value))
) +
geom_point()
ggplot(data=pop2010,
aes(x=value, y=reorder(NAME,value)) ) +
geom_point()
# display the plot
pop_plot
pop_plot <- ggplot(data=pop2010,
aes(x=value, y=reorder(NAME,value)) ) +
geom_point()
# display the plot
pop_plot
pop_plot <- ggplot(data=pop2010,
aes(x=value/1000000), x=reorder(NAME,value)) +
geom_bar(stat="identity") +
theme_minimal() +
labs(title = "2010 US Population by State") +
xlab("State") +
ylab("in millions")
# display the plot
pop_plot
pop_plot <- ggplot(data=pop2010,
aes(x=value/1000000), y=reorder(NAME,value)) +
geom_bar(stat="identity") +
theme_minimal() +
labs(title = "2010 US Population by State") +
xlab("State") +
ylab("in millions")
# display the plot
pop_plot
pop_plot <- ggplot(data=pop2010,
aes(x=value/1000000), y=reorder(NAME,value)) +
geom_bar(stat="identity") +
theme_minimal() +
labs(title = "2010 US Population by State") +
xlab("State") +
ylab("in millions")
# display the plot
pop_plot
pop_plot <- ggplot(data=pop2010,
aes(x=value/1000000, y=reorder(NAME,value)) +
geom_bar(stat="identity") +
theme_minimal() +
labs(title = "2010 US Population by State") +
xlab("State") +
ylab("in millions")
# display the plot
pop_plot
pop_plot <- ggplot(data=pop2010,
aes(x=value/1000000, y=reorder(NAME,value)) ) +
geom_bar(stat="identity") +
theme_minimal() +
labs(title = "2010 US Population by State") +
xlab("State") +
ylab("in millions")
# display the plot
pop_plot
vars2010 <- load_variables(year=2010, # Year or end year for ACS-5yr
dataset = 'sf1', # 'sf1' for decennial census
cache = TRUE) # Save fetched data locally
# How large is the output
dim(vars2010)
# Take a look with head or View
head(vars2010)
View(vars2010)
ca_tract_pop2010 <- get_decennial(geography = "tract", # census tab unit
variables = "P001001", # var of interest
year = 2010, # census year
state='CA') # State filter
# How many tracts in CA
dim(ca_tract_pop2010)
# take a look
head(ca_tract_pop2010)
tract_pop2010 <- get_decennial(geography = "tract", # census tabulation unit
variables = "P001001", # variable of interest
year = 2010, # census year - only one!
state="CA", # limit to California
county=c("Alameda","Contra Costa")) # & counties
dim(tract_pop2010)
#urban and rural pop for 3 CA counties
ur_pop10 <- get_decennial(geography = "county", # census tabulation unit
variables = c(urban="P002002",rural="P002005"),
year = 2010,
summary_var = "P002001", # The denominator
state='CA',
county=c("Napa","Sonoma","Mendocino"))
ur_pop10
# Calculate the percent of population that is Urban or Rural
ur_pop10 <- ur_pop10 %>%
mutate(pct = 100 * (value / summary_value))
# Take a look at the output.
ur_pop10 # Take a look
myplot <- ggplot(data = ur_pop10,
mapping = aes(x = NAME, fill = variable,
y = ifelse(test = variable == "urban",
yes = -pct, no = pct))) +
geom_bar(stat = "identity") +
scale_y_continuous(labels = abs, limits=c(-100,100)) +
labs(title="Urban & Rural Population in Wine Country",
x="County", y = " Percent of Population", fill="") +
coord_flip()
# plot it
myplot
# Fetch 2000 population data by state
pop2000 <- get_decennial(geography = "state",
variables = c(pop2000="P001001"),
year = 2000)
# Fetch 2010 population data by state
pop2010 <- get_decennial(geography = "state",
variables = c(pop2010="P001001"),
year = 2010)
# Use tidyverse `bind_rows` function to combine the data for these years
state_pop <- bind_rows(pop2000, pop2010)
# Take a look with head or View
head(state_pop)
# Tigris options - used by tidycensus
# Cache retrieved geographic data locally
options(tigris_use_cache = TRUE)
pop2010geo <- get_decennial(geography = "state",
variables = c(pop10="P001001"),
year = 2010,
output="wide",
geometry=TRUE) # Fetch geometry data for mapping
head(pop2010geo, 3)
plot(pop2010geo$geometry)
plot(pop2010geo$geometry)
plot(pop2010geo)
pop2010geo_shifted <- get_decennial(geography = "state",
variables = c(pop10="P001001"),
output="wide",
year = 2010,
geometry=TRUE,
shift_geo=TRUE)
## Shift Happens!
plot(pop2010geo_shifted$geometry)
st_write(pop2010geo_shifted, "data_out/usa_pop2010_shifted.shp")
# Check to see if the data was written out to a shapefile
dir("data_out")
plot(pop2010geo_shifted['pop10']) # a choropleth map!
ggplot(pop2010geo_shifted, aes(fill = pop10)) +
geom_sf() # tells ggplot that geographic data are being plotted
ggplot(pop2010geo_shifted, aes(fill = pop10)) +
geom_sf(color=NA) + # What does color=NA do
coord_sf(crs = 3857) + # Dynamically change the CRS
scale_fill_viridis_c(option = "viridis") # Change the color palette
# Try different options, e.g.
# plasma, magma, inferno, cividis
bay_counties <- c("Alameda", "Contra Costa", "Marin", "San Francisco",
"Sonoma", "Napa","Solano", "San Mateo", "Santa Clara")
bayarea_pop10 <- get_decennial(geography = "tract",
variables = "P001001",
year = 2010,
state='CA',
county=bay_counties,
geometry=T)
# take a look
head(bayarea_pop10)
# Quick map
plot(bayarea_pop10['value'])
vars_acs2019 <- load_variables(year=2019, # end year 2016-2020 period
dataset = 'acs5', # the ACS data product
cache = T) # Save locally for future access
# how many variables?
dim(vars_acs2019)
View(vars_acs2019)
alco_mhhincome <- get_acs(geography='tract',
variables=c(median_hhincome = "B19013_001"),
year = 2019,
state='CA',
county='Alameda',
geometry=TRUE
)
head(alco_mhhincome)
plot(alco_mhhincome['estimate'])
# Median household income by race/ethnicity: Variables from ACS 2015—19
#All households = "B19013_001",
inc_by_race <- c(White = "B19013H_001",
Black = "B19013B_001",
Asian = "B19013D_001",
Hispanic = "B19013I_001" )
alco_mhhinc_by_race <- get_acs(geography='tract',
variables=inc_by_race,
year = 2019,
state='CA',
county='Alameda',
geometry=T )
# Create the map
medhhinc_facet_map <- alco_mhhinc_by_race %>%
ggplot(aes(fill = estimate)) +
facet_wrap(~variable) +
geom_sf(color=NA) +
scale_fill_viridis_c(option="magma")
# Display the map
medhhinc_facet_map
mapview(alco_mhhincome)
mapview(alco_mhhincome, zcol="estimate")
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(echo = TRUE)
get_decennial()
sessionInfo()
# Create a list of the packages we will use
list_of_packages <- c("tidyverse","sf","mapview","tigris", "tidycensus")
# Identify any new packages that will need to be installed
new_packages <- list_of_packages[!(list_of_packages %in% installed.packages()[,"Package"])]
# Install any packages that are not installed (new_packages)
if(length(new_packages) > 0) {
print(paste("Installing these packages:", new_packages))
install.packages(new_packages)
} else {
print("All packages already installed!")
}
# Install any packages that are not installed (new_packages)
if(length(new_packages) > 0) {
print(paste("Installing these packages:", new_packages))
install.packages(new_packages)
} else {
print("All packages already installed!")
}
library(tidycensus)
library(tidyverse)
library(sf)
library(mapview)
# source (run) an r script that creates a variable with my key
source("../../keys/census_api_key.R")
# register the key
census_api_key(key = my_census_api_key)
pop2010 <- get_decennial(geography = "state", # census tabulation unit
variables = "P001001", # variable(s) of interest
year = 2010) # census year
head(pop2010)
# wide format
pop2010w <- get_decennial(geography = "state", # census tabulation unit
variables = "P001001", # variable(s) of interest
year = 2010, # census year
output="wide") # get output in wide format
head(pop2010w)
get_decennial(geography = "county", # census tabulation unit
variables = "P001001", # variable(s) of interest
year = 2010, # census year
state='CA') # Filter by state is CA
get_decennial(geography = "county", # census tabulation unit
variables = "P001001", # variable(s) of interest
year = 2010, # census year
state='CA', # Filter by state is CA
county='Alameda') # Filter by county Alameda
pop_plot <- ggplot(data=pop2010,
aes(x=value, y=reorder(NAME,value)) ) +
geom_point()
# display the plot
pop_plot
pop_plot <- ggplot(data=pop2010,
aes(x=value, y=reorder(NAME,value)) ) +
geom_point()
# display the plot
pop_plot
pop_plot <- ggplot(data=pop2010,
aes(x=value/1000000, y=reorder(NAME,value)) ) +
geom_bar(stat="identity") +
theme_minimal() +
labs(title = "2010 US Population by State") +
xlab("State") +
ylab("in millions")
# display the plot
pop_plot
vars2010 <- load_variables(year=2010, # Year or end year for ACS-5yr
dataset = 'sf1', # 'sf1' for decennial census
cache = TRUE) # Save fetched data locally
# How large is the output
dim(vars2010)
# Take a look with head or View
head(vars2010)
## Fetch population by **tract** for California.
ca_tract_pop2010 <- get_decennial(geography = "tract", # census tab unit
variables = "P001001", # var of interest
year = 2010, # census year
state='CA') # State filter
## Fetch population by **tract** for California.
ca_tract_pop2010 <- get_decennial(geography = "tract", # census tab unit
variables = "P001001", # var of interest
year = 2010, # census year
state='CA') # State filter
# How many tracts in CA
dim(ca_tract_pop2010)
# take a look
head(ca_tract_pop2010)
tract_pop2010 <- get_decennial(geography = "tract", # census tabulation unit
variables = "P001001", # variable of interest
year = 2010, # census year - only one!
state="CA", # limit to California
county=c("Alameda","Contra Costa")) # & counties
dim(tract_pop2010)
#urban and rural pop for 3 CA counties
ur_pop10 <- get_decennial(geography = "county", # census tabulation unit
variables = c(urban="P002002",rural="P002005"),
year = 2010,
summary_var = "P002001", # The denominator
state='CA',
county=c("Napa","Sonoma","Mendocino"))
ur_pop10
# Calculate the percent of population that is Urban or Rural
ur_pop10 <- ur_pop10 %>%
mutate(pct = 100 * (value / summary_value))
# Take a look at the output.
ur_pop10
myplot <- ggplot(data = ur_pop10,
mapping = aes(x = NAME, fill = variable,
y = ifelse(test = variable == "urban",
yes = -pct, no = pct))) +
geom_bar(stat = "identity") +
scale_y_continuous(labels = abs, limits=c(-100,100)) +
labs(title="Urban & Rural Population in Wine Country",
x="County", y = " Percent of Population", fill="") +
coord_flip()
# plot it
myplot
# Fetch 2000 population data by state
pop2000 <- get_decennial(geography = "state",
variables = c(pop2000="P001001"),
year = 2000)
# Fetch 2010 population data by state
pop2010 <- get_decennial(geography = "state",
variables = c(pop2010="P001001"),
year = 2010)
# Use tidyverse `bind_rows` function to combine the data for these years
state_pop <- bind_rows(pop2000, pop2010)
# Take a look with head or View
head(state_pop)
tail(state_pop)
# Tigris options - used by tidycensus
# Cache retrieved geographic data locally
options(tigris_use_cache = TRUE)
pop2010geo <- get_decennial(geography = "state",
variables = c(pop10="P001001"),
year = 2010,
output="wide",
geometry=TRUE) # Fetch geometry data for mapping
head(pop2010geo, 3)
# plot the geometry column data
plot(pop2010geo$geometry)
pop2010geo_shifted <- get_decennial(geography = "state",
variables = c(pop10="P001001"),
output="wide",
year = 2010,
geometry=TRUE,
shift_geo=TRUE)
## Shift Happens!
plot(pop2010geo_shifted$geometry)
st_write(pop2010geo_shifted, "data_out/usa_pop2010_shifted.shp")
# Check to see if the data was written out to a shapefile
dir("data_out")
# Name the column with the variable values to make
# a thematic map, also called a choropleth map.
plot(pop2010geo_shifted['pop10'])
ggplot(pop2010geo_shifted, aes(fill = pop10)) +
geom_sf() # tells ggplot that geographic data are being plotted
ggplot(pop2010geo_shifted, aes(fill = pop10)) +
geom_sf(color=NA) + # What does color=NA do
coord_sf(crs = 3857) + # Dynamically change the CRS
scale_fill_viridis_c(option = "viridis") # Change the color palette
bay_counties <- c("Alameda", "Contra Costa", "Marin", "San Francisco",
"Sonoma", "Napa","Solano", "San Mateo", "Santa Clara")
bayarea_pop10 <- get_decennial(geography = "tract",
variables = "P001001",
year = 2010,
state='CA',
county=bay_counties,
geometry=T)
bayarea_pop10 <- get_decennial(geography = "tract",
variables = "P001001",
year = 2010,
state='CA',
county=bay_counties,
geometry=T)
# Quick map
plot(bayarea_pop10['value'])
vars_acs2019 <- load_variables(year=2019, # end year 2016-2020 period
dataset = 'acs5', # the ACS data product
cache = T) # Save locally for future access
# how many variables?
dim(vars_acs2019)
alco_mhhincome <- get_acs(geography='tract',
variables=c(median_hhincome = "B19013_001"),
year = 2019,
state='CA',
county='Alameda',
geometry=TRUE
)
head(alco_mhhincome)
plot(alco_mhhincome['estimate'])
# Median household income by race/ethnicity: Variables from ACS 2015—19
#All households = "B19013_001",
inc_by_race <- c(White = "B19013H_001",
Black = "B19013B_001",
Asian = "B19013D_001",
Hispanic = "B19013I_001" )
alco_mhhinc_by_race <- get_acs(geography='tract',
variables=inc_by_race,
year = 2019,
state='CA',
county='Alameda',
geometry=T )
# Create the map
medhhinc_facet_map <- alco_mhhinc_by_race %>%
ggplot(aes(fill = estimate)) +
facet_wrap(~variable) +
geom_sf(color=NA) +
scale_fill_viridis_c(option="magma")
# Display the map
medhhinc_facet_map
mapview(alco_mhhincome)
mapview(alco_mhhincome, zcol="estimate")