This notebook demonstrates the basics of mapping data in IPython. All you need is a simple dataset, containing coordinate values.
In [1]:
%pylab inline
from pylab import *
pylab.rcParams['figure.figsize'] = (8.0, 6.4)
In [2]:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
And now let's test if the Basemap package is loaded and the graphics displayed correctly.
In [3]:
map = Basemap(projection='ortho', lat_0=50, lon_0=-100,
resolution='l', area_thresh=1000.0)
map.drawcoastlines()
plt.show()
Now to the cool part!
In [4]:
import csv
# Open the cities population data file.
filename = 'city_longlat.csv'
# Create empty lists for the latitudes, longitudes and population.
lats, lons, population = [], [], []
# Read through the entire file, skip the first line,
# and pull out the data we need.
with open(filename) as f:
# Create a csv reader object.
reader = csv.reader(f)
# Ignore the header row.
next(reader)
# Store the latitudes, longitudes and populations in the appropriate lists.
for row in reader:
lats.append(float(row[1]))
lons.append(float(row[2]))
population.append(float(row[3]))
# --- Build Map ---
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
def get_marker_color(population):
if population < 2000000:
return ('ro')
elif population < 7000000:
return ('yo')
else:
return ('go')
map = Basemap(projection='merc', resolution = 'h', area_thresh = 1000.0,
lat_0=0, lon_0=-130,
llcrnrlon=-18.968978, llcrnrlat=33.679432,
urcrnrlon=41.968945, urcrnrlat=58.940191)
map.drawcoastlines()
map.drawcountries()
map.bluemarble()
map.drawmapboundary()
map.drawmeridians(np.arange(0, 360, 30))
map.drawparallels(np.arange(-90, 90, 30))
for lons, lats, population in zip(lons, lats, population):
x,y = map(lats, lons)
marker_string = get_marker_color(population)
map.plot(x, y, marker_string, markersize=population/150000)
title_string = "Most Populous Cities in Europe"
figsize(18, 12)
plt.title(title_string)
plt.show()
The green circle represents the cities with population above 7 million inhabitants, the yellow between 2 and 7 million, and the red represents all others.