Map of the US
Do you know the fifty nifty United States from thirteen original colonies? If you don’t, that’s ok, because we have google!
Here is the tutorial I followed to create the US map in python.
https://jcutrer.com/python/learn-geopandas-plotting-usmaps
I’m going to go through ^ tutorial and add a couple things I couldn’t find in plain sight from the tutorial. First off, this site:
^This site has all the US area files (shapefiles/whatever that means).
1. As usual:
import pandas as pd
import geopandas
import math
import matplotlib.pyplot as plt
2. Make sure to download all the files in the states_2020 folder
I believe I used the 500,000 (national) shapefile. At first I made the mistake of only downloading the shp file. For some reason, the shp file won’t run unless all the other files in the states_2020 folder are downloaded. Make sure to extract the files from the zip file before loading into python (unless you know how to load in a zip file).
states = geopandas.read_file('states_2020/cb_2020_us_state_5m.shp')
states.head()
If you write states.shape you will notice the website provides you with 56 states/locations! states.shape should return (56, 10)
3. PolygonPatch
To install: pip install -i https://pypi.anaconda.org/mkhines/simple descartes
from descartes.patch import PolygonPatch
4. Make a mini plot
states.plot();
5. Get rid of excess states
I had to make a map for a project at work so my boss helped me with this line of code. Why did I not know ~ meant not? Oh well, I guess I’ll always be learning.
states_50 = states[~states['STUSPS'].isin(['GU', 'AS', 'AK', 'PR', 'VI', 'MP'])]
states_50.head()
Now when you do states_50.shape you will see (50,10)
states_50.plot();
6. Boundary plot
states_50.boundary.plot(figsize=(40,15))
7. Labeled US map
fig, ax = plt.subplots(figsize=(29,12))
states_50.apply(lambda x: ax.annotate(s=x.STUSPS, xy=x.geometry.centroid.coords[0], ha='center', fontsize=11, color = 'black'), axis=1);
states_50.boundary.plot(ax=ax, color='black', linewidth = .2)
states_50.plot(ax=ax, cmap = 'Blues')plt.savefig('US_state_map')
The cool thing about cmap is all the color options! Personally, I didn’t think the flag option was that cool looking.
fig, ax = plt.subplots(figsize=(29,12))
states_50.apply(lambda x: ax.annotate(s=x.STUSPS, xy=x.geometry.centroid.coords[0], ha='center', fontsize=11, color = 'white'), axis=1);
states_50.boundary.plot(ax=ax, color='black', linewidth = .2)
states_50.plot(ax=ax, cmap = 'flag')
The following link has a list of cmap color options:
If you could travel to any state to get a bagel, which place in NJ would you go?