Tutorial 4: Working with Geometries¶
cendat can fetch geographic boundaries alongside your data for mapping.
Goal: Get race data with geometries for US regions.
Setup¶
In [ ]:
Copied!
import os
from cendat import CenDatHelper
from dotenv import load_dotenv
load_dotenv()
cdh = CenDatHelper(key=os.getenv("CENSUS_API_KEY"))
cdh.list_products(years=[2011], patterns=r"acs/acs5\)")
cdh.set_products()
import os
from cendat import CenDatHelper
from dotenv import load_dotenv
load_dotenv()
cdh = CenDatHelper(key=os.getenv("CENSUS_API_KEY"))
cdh.list_products(years=[2011], patterns=r"acs/acs5\)")
cdh.set_products()
Step 2: Select Data and Geography¶
In [ ]:
Copied!
cdh.list_groups(patterns=r"^race")
cdh.list_groups(patterns=r"^race")
In [ ]:
Copied!
cdh.set_groups(["B02001"])
cdh.describe_groups()
cdh.set_groups(["B02001"])
cdh.describe_groups()
In [ ]:
Copied!
# 020 = Region
cdh.set_geos(["020"])
# 020 = Region
cdh.set_geos(["020"])
Step 3: Get Data with Geometry¶
In [ ]:
Copied!
response = cdh.get_data(
include_names=True,
include_geometry=True # This fetches boundaries from TIGERweb
)
response = cdh.get_data(
include_names=True,
include_geometry=True # This fetches boundaries from TIGERweb
)
Step 4: Convert to GeoDataFrame¶
In [ ]:
Copied!
# to_gpd() returns a GeoDataFrame ready for mapping
gdf = response.to_gpd(destring=True, join_strategy="inner")
print(gdf)
# to_gpd() returns a GeoDataFrame ready for mapping
gdf = response.to_gpd(destring=True, join_strategy="inner")
print(gdf)
In [ ]:
Copied!
# Use with matplotlib, folium, or your preferred mapping library
gdf.plot(column="B02001_001E", legend=True)
# Use with matplotlib, folium, or your preferred mapping library
gdf.plot(column="B02001_001E", legend=True)
Note - Supported Geographies
Geometry fetching currently supports: regions (020), divisions (030), states (040), counties (050), county subdivisions (060), census tracts (140), block groups (150), and places (160).