Building 2-layer maps - combining polygons and scatterplots
In this chapter, you will learn how to create a two-layer map by first plotting regions from a shapefile and then plotting location points as a scatterplot. This is the Summary of lecture "Visualizing Geospatial Data in Python", via datacamp.
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (10, 5)
father_son = pd.read_csv('./dataset/father_son.csv', usecols=['fheight', 'sheight'])
father_son.head()
plt.scatter(father_son.fheight, father_son.sheight, c='darkred', marker='s');
plt.scatter(father_son.fheight, father_son.sheight, c = 'yellow', edgecolor= 'darkblue');
plt.scatter(father_son.fheight, father_son.sheight, c = 'yellow', edgecolor = 'darkblue');
plt.grid();
plt.xlabel('father height (inches)');
plt.ylabel('son height (inches)');
plt.title('Son Height as a Function of Father Height');
chickens = pd.read_csv('./dataset/chickens.csv')
# Look at the first few rows of the chickens DataFrame
print(chickens.head())
# Plot the locations of all Nashville chicken permits
plt.scatter(x=chickens.lng, y=chickens.lat);
We can see the relative location of the Nashville chickens using longitude for the x-axis and latitude for the y-axis. Next, now you'll up your game by plotting the locations on an actual map!
Note: if you use anaconda on windows, you must be faced in GDAL error. At that case, follow the instruction here
import geopandas as gpd
# Read in the services district shapefile and look at the first few rows
service_district = gpd.read_file('./dataset/ServiceDistricts.shp')
print(service_district.head())
# Print the contents of the service districts geometry in the first row
# print(service_district.loc[0, 'geometry'])
The geometry field holds a series of latitude/longitude pairs that define the border of a polygon. Printing a geometry field gives all of the latitude/longitude pairs that make up the polygon boundary.
service_district.to_crs(epsg=4326).plot(figsize=(10, 10));
# Plot the Service Districts, color them according to name, and show a legend
service_district.to_crs(epsg=4326).plot(column='Name', legend=True, figsize=(10, 10));
service_district.to_crs(epsg=4326).plot(column='Name', figsize=(10, 10));
# Add the chicken locations
plt.scatter(x=chickens.lng, y=chickens.lat, c='black');
service_district.to_crs(epsg=4326).plot(column='Name', legend=True);
# Add the chicken locations
plt.scatter(x=chickens.lng, y=chickens.lat, c='black', edgecolor='white');
# Add labels and title
plt.title('Nashville Chicken Permits');
plt.xlabel('longitude');
plt.ylabel('latitude');
# Add grid lines
plt.grid();