Maps and Python basics¶
DataCarpentry: quick example of using maps to explain some Python basics
- range function
- range and for loop
- dictionaries
- loop over dictionaries
In [1]:
%matplotlib inline
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
Setting up the map¶
In [2]:
m = Basemap(projection='robin', lon_0=0, resolution=None)
m.shadedrelief(scale=0.2)
Out[2]:
Range function¶
In [3]:
meridians = range(90)
m.drawmeridians(meridians)
print meridians
In [4]:
# start, stop and step
meridians = range(0,360,30)
m.drawmeridians(meridians)
print meridians
In [5]:
# start, stop and step
parallels = range(-90,120,30)
m.drawparallels(parallels)
print parallels
In [6]:
m.shadedrelief(scale=0.2)
m.drawmeridians(meridians)
m.drawparallels(parallels)
plt.show()
Range and for loop¶
In [7]:
for lon in range(0, 360, 30):
m.scatter(lon, 0, latlon=True)
In [8]:
m.shadedrelief(scale=0.2)
for lon in meridians:
for lat in parallels:
m.scatter(lon, lat, latlon=True)
Dictionaries¶
In [9]:
cities = {'newyork': (-74.00597, 40.71427),
'rome': (12.51133, 41.89193),
'capetown': (18.42322, -33.92584)
}
Accessing elements of dictionary¶
In [10]:
m.shadedrelief(scale=0.2)
m.scatter(cities['newyork'][0],
cities['newyork'][1],
color = 'red',
latlon=True
)
m.scatter(cities['rome'][0],
cities['rome'][1],
color = 'green',
latlon=True
)
m.drawgreatcircle(
cities['newyork'][0],
cities['newyork'][1],
cities['rome'][0],
cities['rome'][1]
)
Out[10]:
Loop over dictionaries¶
In [11]:
# loop over values
for p in cities.values():
print p
m.scatter(p[0], p[1], latlon=True)
In [12]:
# loop over keys
for k in cities:
print k
# or
for k in cities.keys():
print k
In [13]:
# loop over keys and values
m.shadedrelief(scale=0.2)
for k, p in cities.iteritems():
print k, p
m.scatter(p[0], p[1], label= k, latlon=True)