<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jose Luis Ruiz on Medium]]></title>
        <description><![CDATA[Stories by Jose Luis Ruiz on Medium]]></description>
        <link>https://medium.com/@jl_ruiz?source=rss-86184b2b81df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1XEJXCxsRpySw1NVUgbyhA.jpeg</url>
            <title>Stories by Jose Luis Ruiz on Medium</title>
            <link>https://medium.com/@jl_ruiz?source=rss-86184b2b81df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:46:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jl_ruiz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Plot maps from the US Census Bureau using Geopandas and Contextily in Python.]]></title>
            <link>https://medium.com/@jl_ruiz/plot-maps-from-the-us-census-bureau-using-geopandas-and-contextily-in-python-df787647ef77?source=rss-86184b2b81df------2</link>
            <guid isPermaLink="false">https://medium.com/p/df787647ef77</guid>
            <category><![CDATA[geopandas]]></category>
            <category><![CDATA[us-census-bureau]]></category>
            <category><![CDATA[contextily]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jose Luis Ruiz]]></dc:creator>
            <pubDate>Wed, 21 Apr 2021 20:52:30 GMT</pubDate>
            <atom:updated>2021-04-22T15:11:37.596Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leverage geopandas and contextily libraries to combine geometrical polygon shapes with raster tilemaps.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3fgsfXOn2967XKJPPECIg.jpeg" /><figcaption>NASA — <a href="https://unsplash.com/s/photos/united-states">United States</a></figcaption></figure><p>In this tutorial, I plan to cover 3 main topics:</p><ol><li>Download shapefiles (*.shp) from the US Census Bureau website.</li><li>Read and create map plots of the US continental states using geopandas.</li><li>Combine <a href="https://geopandas.org/index.html">geopandas </a>and <a href="https://geopandas.org/index.html">contextily </a>to create <em>powerful </em>maps that combine geometrical polygon shapes with raster tile plots.</li></ol><h3>Introduction</h3><p>I do believe that <strong>geopandas</strong> and <strong>contextily</strong> libraries are underutilized in python. <br>Before starting let’s review our main library dependencies.</p><pre>import numpy as np <br>import matplotlib.pyplot as plt <br>import pandas as pd <br>import contextily as ctx <br>import geopandas as gpd <br>import os <br>from mpl_toolkits.axes_grid1 import make_axes_locatable</pre><h3>1. Retrieve TIGER/Line Shapefiles from US Census Bureau</h3><p>Go to the following website and under <strong>“Select a layer type”</strong> choose ‘States and Equivalent’. Press Submit<br><a href="https://www.census.gov/cgi-bin/geo/shapefiles/index.php">https://www.census.gov/cgi-bin/geo/shapefiles/index.php</a></p><p>The main benefit of using shapefiles maps from the US Census Bureau is that you will access maps with ‘official’ nomenclature for states, counties, and postal zip codes. This will facilitate the merge of additional information using the Census or other geostatistical sites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jc7S9gd6Q9E2TiIDV8Upqg.png" /></figure><p>Download and unzip file<strong> tl_2020_us_state.zip<br></strong>Inside the folder <strong>tl_2020_us_state</strong>, you will find the following files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRTvkEhneD0rkYOB27ZvVA.png" /></figure><h3>2. Read <strong>shapefile</strong> using geopandas</h3><p>Run the following code to read the shapefile using <em>geopandas.read</em>.</p><pre>path = &quot;C:<strong>...</strong>tl_2020_us_state\tl_2020_us_state.shp&quot;<br>df = gpd.read_file(path)<br>df = df.to_crs(&quot;EPSG:4326&quot;)</pre><p>Let’s look into the information available for each state:</p><pre><em># Information for each state </em><br>df.iloc[0,:]</pre><pre>REGION                                                      3<br>DIVISION                                                    5<br>STATEFP                                                    54<br>STATENS                                              01779805<br>GEOID                                                      54<br>STUSPS                                                     WV<br>NAME                                            West Virginia<br>LSAD                                                       00<br>MTFCC                                                   G4000<br>FUNCSTAT                                                    A<br>ALAND                                             62266296765<br>AWATER                                              489206049<br>INTPTLAT                                          +38.6472854<br>INTPTLON                                         -080.6183274<br>geometry    POLYGON ((-81.74725450543596 39.09537994722294...<br>Name: 0, dtype: object</pre><p><strong>REGION</strong> Current Census region code<br><strong>DIVISION</strong> Current Census division code<br><strong>STATEFP</strong> Current state Federal Information Processing Series (FIPS) code <strong>STATENS</strong> Current state GNIS code\ <strong>GEOID</strong> State identifier; state FIPS code<br><strong>STUSPS</strong> Current United States Postal Service state abbreviation<br><strong>NAME</strong> Current state name<br><strong>LSAD</strong> Current legal/statistical area description code for state<br><strong>MTFCC</strong> MAF/TIGER feature class code<br><strong>FUNCSTAT</strong> Current functional status<br><strong>ALAND</strong> Current land area (square meters)<br><strong>AWATER</strong> Current water area (square meters<br><strong>INTPTLAT</strong> Current latitude of the internal point<br><strong>INTPTLON</strong> Current longitude of the internal point</p><p>The <strong>geometry</strong> field includes the polygon to draw vectorized maps of each state.</p><p>Let’s create a basic plot</p><pre>df.plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*ihQnC7m70jYj6eV5A6ORUw.png" /></figure><p>As you can see the information retrieval from the US Census Bureau includes all the states and territories of the US. Let’s create a new data frame that includes only the US Continental States excluding Alaska.</p><pre>non_continental = [&#39;HI&#39;,&#39;VI&#39;,&#39;MP&#39;,&#39;GU&#39;,&#39;AK&#39;,&#39;AS&#39;,&#39;PR&#39;]<br>us49 = df<br><strong>for</strong> n <strong>in</strong> non_continental:<br>    us49 = us49[us49.STUSPS != n]</pre><p>Let’s create a simple plot including the boundaries of each state.</p><pre>us49.boundary.plot()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*pzzsbQgwJuAEvHbDy11s1g.png" /></figure><p>Let’s plot a map that includes the ‘land area in square meters’</p><pre>f,ax = plt.subplots(1,1, figsize=(8,6), sharex=True, sharey=True, dpi=300)<br>plt.title(&#39;Simple Map of US States&#39;)<br>divider = make_axes_locatable(ax)<br>cax = divider.append_axes(&quot;right&quot;, size=&quot;3%&quot;,pad=0,alpha=0.5)<br>us49.plot(&#39;ALAND&#39;, ax=ax, alpha=0.5, cmap=&#39;Pastel1&#39;, edgecolor=&#39;k&#39;, legend=True, cax=cax, linewidth=0.1)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_B8NoLoRQyuS1hK7EQaMA.png" /></figure><p>Add new columns in the us49 data frame for land and water of each state in square miles.<br>Add a new variable that calculates the ‘centroid’ of each state</p><pre>us49[&#39;ALAND_miles&#39;] = us49[&#39;ALAND&#39;]*3.86102e-7<br>us49[&#39;AWATER_miles&#39;] = us49[&#39;AWATER&#39;]*3.86102e-7<br>us49[&#39;centroid&#39;] = us49.centroid</pre><p>Let’s plot the centroids for each state</p><pre>f,ax = plt.subplots(1,1, figsize=(8,6), sharex=True, sharey=True, dpi=300)<br>plt.title(&#39;Map of US States with Centroids&#39;)<br>divider = make_axes_locatable(ax)<br>cax = divider.append_axes(&quot;right&quot;, size=&quot;3%&quot;,pad=0,alpha=0.5)<br>us49.plot(&#39;ALAND_miles&#39;, ax=ax, alpha=0.5, cmap=&#39;Pastel1&#39;, edgecolor=&#39;k&#39;, legend=True, cax=cax, linewidth=0.1,label=&#39;Inline label&#39;)<br>plt.ylabel(&#39;Square miles&#39;, fontsize=6)<br>us49[&#39;centroid&#39;].plot(ax=ax, marker=&#39;o&#39;, color=&#39;red&#39;, markersize=5)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOuso8yVExhm6zLY4zcKzQ.png" /></figure><p>Create a function to plot specific data from file:<br><strong>df</strong> = data frame to plot<br><strong>data</strong> = with the current file you can select either the ALAND (land area) or AWATER (water area)<br><strong>cmap</strong> = defines the colormaps to use in the matplot (i.e. summer, viridis.) for a selection of different cmaps refer to <a href="https://matplotlib.org/stable/tutorials/colors/colormaps.html">colormaps in matplotlib</a></p><pre><strong>def </strong>StatesPlot(df,data, cmap):</pre><pre>    f,ax = plt.subplots(1,1, figsize=(15,10), <br>    sharex=True, sharey=True, dpi=300)<br>    f.tight_layout()<br>    plt.title(&#39;United States Map - Variable = &#39; + data)<br>    ax.set_axis_off()<br>    divider = make_axes_locatable(ax)<br>    cax = divider.append_axes(&quot;right&quot;, size=&quot;3%&quot;, <br>    pad=0.5,alpha=0.5)<br>    df.plot(data, ax=ax, alpha=0.5, cmap=cmap, <br>    edgecolor=&#39;k&#39;, legend=True, cax=cax, linewidth=0.1)<br>    plt.ylabel(&#39;Square miles&#39;, fontsize=12)<br>    plt.show()</pre><p>Use the StatesPlot function to create a map of the <strong>‘land area’</strong> per state using <strong>‘summer’</strong> cmap.</p><pre>StatesPlot(us49,&#39;ALAND_miles&#39;, &#39;summer&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTvAKWXpgAy5QsjjZJMywQ.png" /></figure><h3>3. Add Contextly to our geopandas maps to include geo tiles.</h3><p>contextily retrieves tile maps from the internet. It can add those tiles as base map to matplotlib figures or write tile maps to disk into geospatial raster files. <a href="https://contextily.readthedocs.io/en/latest/index.html">Link</a></p><pre>data=&#39;ALAND_miles&#39;<br>cmap=&#39;Spectral&#39;<br>zoom=5<br>dpi=100<br><br><em>#w,s,e,n = states.total_bounds</em><br><br>us49.crs = &quot;EPSG:4326&quot;<br><br>f,ax = plt.subplots(1,1, figsize=(20,12), sharex=<strong>True</strong>, sharey=<strong>True</strong>, dpi=dpi)<br>f.tight_layout(pad=0.8)<br>ax.set_axis_off()<br>plt.title(&#39;US Map using Contextily&#39;,fontsize=&#39;large&#39;)<br>divider = make_axes_locatable(ax)<br>cax = divider.append_axes(&quot;right&quot;, size=&quot;3%&quot;, pad=0.2)<br>ux = us49.to_crs(epsg=3857).plot(data, ax=ax, edgecolor=&#39;k&#39;, cmap=cmap, alpha = 0.2, legend=<strong>True</strong>, cax=cax)<br>ctx.add_basemap(ux, zoom=zoom,source=ctx.providers.OpenStreetMap.Mapnik);<br>plt.ylabel(&#39;Million square miles&#39;, fontsize=12)<br><em># Use savefig to save your map</em><br>plt.savefig(&#39;US Contextily Map with zoom = &#39; + str(zoom) +&#39; .png&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8QXzqebtUnEQQdGUwMKP4w.png" /></figure><p>Contextily offers several providers of tiles for your maps for a list of providers included in contextily run the following code</p><pre><strong>ctx.providers.keys()</strong></pre><pre>Output:<br>dict_keys([&#39;OpenStreetMap&#39;, &#39;OpenSeaMap&#39;, &#39;OpenPtMap&#39;, &#39;OpenTopoMap&#39;, &#39;OpenRailwayMap&#39;, &#39;OpenFireMap&#39;, &#39;SafeCast&#39;, &#39;Thunderforest&#39;, &#39;OpenMapSurfer&#39;, &#39;Hydda&#39;, &#39;MapBox&#39;, &#39;Stamen&#39;, &#39;Esri&#39;, &#39;OpenWeatherMap&#39;, &#39;HERE&#39;, &#39;FreeMapSK&#39;, &#39;MtbMap&#39;, &#39;CartoDB&#39;, &#39;HikeBike&#39;, &#39;BasemapAT&#39;, &#39;nlmaps&#39;, &#39;NASAGIBS&#39;, &#39;NLS&#39;, &#39;JusticeMap&#39;, &#39;Wikimedia&#39;, &#39;GeoportailFrance&#39;, &#39;OneMapSG&#39;])</pre><p>Create a new function to plot a specific state 2 letter code with a specific resolution (zoom) and density (dpi = dots per inch).</p><pre><em># list of states using STUSPS</em><br><strong>us49[&#39;STUSPS&#39;].unique()</strong></pre><pre>Output:<br>array([&#39;WV&#39;, &#39;FL&#39;, &#39;IL&#39;, &#39;MN&#39;, &#39;MD&#39;, &#39;RI&#39;, &#39;ID&#39;, &#39;NH&#39;, &#39;NC&#39;, &#39;VT&#39;, &#39;CT&#39;,&#39;DE&#39;, &#39;NM&#39;, &#39;CA&#39;, &#39;NJ&#39;, &#39;WI&#39;, &#39;OR&#39;, &#39;NE&#39;, &#39;PA&#39;, &#39;WA&#39;, &#39;LA&#39;, &#39;GA&#39;,&#39;AL&#39;, &#39;UT&#39;, &#39;OH&#39;, &#39;TX&#39;, &#39;CO&#39;, &#39;SC&#39;, &#39;OK&#39;, &#39;TN&#39;, &#39;WY&#39;, &#39;ND&#39;, &#39;KY&#39;,&#39;ME&#39;, &#39;NY&#39;, &#39;NV&#39;, &#39;MI&#39;, &#39;AR&#39;, &#39;MS&#39;, &#39;MO&#39;, &#39;MT&#39;, &#39;KS&#39;, &#39;IN&#39;, &#39;SD&#39;,&#39;MA&#39;, &#39;VA&#39;, &#39;DC&#39;, &#39;IA&#39;, &#39;AZ&#39;], dtype=object)</pre><p>statePlot function</p><pre><strong>def</strong> statePlot(st,data,cmap,zoom,dpi):<br>    state = us49.loc[us49[&#39;STUSPS&#39;] == st]<br>    state.crs = &quot;EPSG:4326&quot;<br>    f,ax = plt.subplots(1,1, figsize=(8,8), <br>    sharex=<strong>True</strong>,sharey=<strong>True</strong>, dpi=dpi)<br>    f.tight_layout(pad=0.8)<br>    ax.set_axis_off()<br>    plt.title(&#39;Map using Contextily - &#39; + data,fontsize=&#39;large&#39;)<br>    divider = make_axes_locatable(ax)<br>    cax = divider.append_axes(&quot;right&quot;, size=&quot;3%&quot;, pad=0.2)<br>    ux = state.to_crs(epsg=3857).plot(data, ax=ax, <br>    edgecolor=&#39;blue&#39;,    cmap=cmap, alpha = 0.2, <br>    legend=<strong>True</strong>, cax=cax)<br>    ctx.add_basemap(ux,    zoom=zoom,<br>     source=ctx.providers.OpenStreetMap.Mapnik);<br>    plt.ylabel(&#39;Million square miles&#39;, fontsize=12)<br>    <em># Use savefig to save your map</em><br>    plt.savefig(<br>    &#39;US Contextily Map with zoom = &#39; + str(zoom) +&#39; .png&#39;)<br>    plt.show()</pre><p>Map plot of California (‘CA’) with zoom factor = 5 and dpi = 200</p><pre>statePlot(&#39;CA&#39;,&#39;ALAND_miles&#39;,&#39;summer&#39;,5,200)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ngfvkux44SBcocQBTTsBew.png" /></figure><p>Same plot but with zoom factor = 9 and dpi = 300</p><pre>statePlot(&#39;CA&#39;,&#39;ALAND_miles&#39;,&#39;summer&#39;,9,300)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iseoyRIxjFm9_7PjXSDV-g.png" /></figure><p>All maps were will be saved into your working directory as ‘png’ files.</p><h3>Get the Jupyter Notebook files of this tutorial on Git Hub.</h3><p><a href="https://github.com/TuunicoApp/US_Census_Maps">TuunicoApp/US_Census_Maps</a></p><p>Hope you find this tutorial useful. Your feedback is more than welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df787647ef77" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>