maps_and_python_basics

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]:
<matplotlib.image.AxesImage at 0x7effbf584990>

Range function

In [3]:
meridians = range(90)

m.drawmeridians(meridians)
print meridians
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89]
In [4]:
# start, stop and step
meridians = range(0,360,30)

m.drawmeridians(meridians)
print meridians
[0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330]
In [5]:
# start, stop and step
parallels = range(-90,120,30)

m.drawparallels(parallels)
print parallels
[-90, -60, -30, 0, 30, 60, 90]
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]:
[<matplotlib.lines.Line2D at 0x7effbdadc990>]

Loop over dictionaries

In [11]:
# loop over values

for p in cities.values():
    print p
    m.scatter(p[0], p[1], latlon=True)
(-74.00597, 40.71427)
(18.42322, -33.92584)
(12.51133, 41.89193)
In [12]:
# loop over keys

for k in cities:
    print k

# or
for k in cities.keys():
    print k
newyork
capetown
rome
newyork
capetown
rome
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)
newyork (-74.00597, 40.71427)
capetown (18.42322, -33.92584)
rome (12.51133, 41.89193)