Python Shapefile – How to Plot Scatter Plots Over a Shapefile

pythonscatterplotshapefile

This is my code:

import matplotlib.pyplot as plt
import json
import time
import geopandas as gpd
from descartes import PolygonPatch
from shapely.geometry import LineString

borough = gpd.read_file('London_Borough_Excluding_MHW.shp')
borough = borough.to_crs({'init': 'epsg:4326'})

fig = plt.figure(figsize=(20, 8)) 
ax = borough.plot()

x, y = ax(df2['lon'].values, df2['lat'].values)
ax.scatter(x,y, marker="*", color='r', alpha=0.7, zorder=5, s=2)
plt.show

This is the error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-5f23b6559223> in <module>
     12 ax = borough.plot()
     13 
---> 14 x, y = ax(df2['lon'].values, df2['lat'].values)
     15 ax.scatter(x,y, marker="*", color='r', alpha=0.7, zorder=5, s=2)
     16 plt.show

TypeError: 'AxesSubplot' object is not callable

and this is the result I got:

Graph

Best Answer

The plot() method returns an AxesSubplot object which you are storing as ax. This object has various methods and properties (as you figured out by calling ax.scatter()) but is is not callable itself; this means you can't run ax(). To get the x and y coordinates, remove that call from the following line:

x, y = ax(df2['lon'].values, df2['lat'].values)

so it becomes:

x, y = df2['lon'].values, df2['lat'].values

This way you'll end up with an array of longitude coordinates (x) and an array of latitude coordinates (y).

Regarding the size of your points, it is controlled by the s parameter in the scatter function. You can play around with this value until you are comfortable with the size of the points. For example:

ax.scatter(x, y, marker="*", color='r', alpha=0.7, zorder=5, s=10)
Related Question