Using Geopandas to Plot Coordinates On a Map
Have you ever wanted to plot longitude and latitude coordinates, but your output looks like this? :
Clearly the figure above represents a map of the US, but there is no background map behind it to tell where everything is. This is one problem GeoPandas can fix!
Geopandas is an excellent resource that can be used in data science when plotting maps and coordinates. I have used it in some of my projects when I have wanted to look at where my locations are on a map. Geopandas is also useful because you can import custom shapefiles as well as use some preset maps.
To begin install Geopandas as followed:
pip install geopandas
Then import Geopandas, as well as any needed packages.
import geopandas as gpd
from geopandas import GeoDataFrame
"gpd" is the conventional way of naming Geopandas. GeoDataFrame is also needed as it is used to create a Geopandas dataframe.
Next you can import your shapefile. When using shapefiles, make sure you import all of the correct files into your workspace. Shapefiles are composed of 3 mandatory files .shp, .shx and .dbf. I used a shapefile that has the map of the 50 states. Then read the .shp file like this:
state_map = gpd.read_file('/content/s_08mr23.shp'
Then follow the code below. Here the columns 'LONGITUD' and 'LATITUDE' are used for the x,y coordinates.
# zip x and y coordinates into single feature
geometry = [Point(xy) for xy in zip(df['LONGITUD'], df['LATITUDE'])]
# create GeoPandas dataframe
gdf = GeoDataFrame(df, geometry=geometry)
# create figure and axes, assign to subplot
fig, ax = plt.subplots(figsize=(15,15))
state_map.plot(ax=ax, alpha=0.4,color='blue')
gdf.plot(ax=ax,alpha=0.5, legend=True,markersize = 5, marker='o', color='red')
# add title to graph
plt.title('US Map', fontsize=15,fontweight='bold')
# set latitiude and longitude boundaries for map display
plt.xlim(-185, -60)
plt.ylim(15 , 80)
# show map
plt.show())
A figure is created, points are plotted, and color, labels, and titles are added. I also restricted the map to only show certain longitudes and latitudes to prevent the map from showing excess areas not in the shapefile.
The map looks like this:
And that's how to show coordinates by using GeoPandas in Python! You can also use different shapefiles with different layers, topography, and other mapping related features.
This is great! I love that it's not an overly complicated example, it just shows how to make nicer graphs.