Deepak M Deepak M - 23 days ago 7
Python Question

Plotting a Map with geopy and matplotlib in Jupyter Notebook

Hello I am trying to plot a map of the US and mark the various cities across the country. I got the map to work. But i am having two issues. The first is, I am getting this error message:

AttributeError: 'NoneType' object has no attribute 'longitude'


Secondly, I have tried to enlarge the graph using the plt.figsize attribute however my map still stays the same size.

Lastly, This is not really an issue but what if i wanted to label the dots with the city names How can i do so?

Here is my code for the map:

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from geopy.geocoders import Nominatim
import math

city_list = list(flight_data["OriginCityName"].unique())
cities = city_list
scale = 1

map = Basemap(width=10000000,height=6000000,projection='lcc',
resolution=None,lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.)
plt.figure(figsize=(19,20))
map.bluemarble()


# Get the location of each city and plot it
geolocator = Nominatim()
for city in cities:
loc = geolocator.geocode(city)
if not loc:
print("Could not locate {}".format(city))
continue
x, y = map(loc.longitude, loc.latitude)
map.plot(x,y,marker='o',color='Red',markersize=5)
plt.annotate(city, xy = (x,y), xytext=(-20,20))
plt.show()


enter image description here

Answer
  1. I guess there is something in your city_list Nominatim can't resolve. I added a check for that below.

  2. You have to call figure(num=1,figsize=(8,9)) before you plot anything (here: the map).

  3. You can use plt.annotate, see below.

Hope this helps.

    for city in cities:
        loc = geolocator.geocode(city)
        if not loc:
            print("Could not locate {}".format(city))
            continue
        x, y = map(loc.longitude, loc.latitude)
        map.plot(x,y,marker='o',color='Red',markersize=int(math.sqrt(count))*scale)
        plt.annotate(city, xy = (x,y), xytext=(-20,20)) 
Comments