Practice Problem - Map of Temperatures over Germany - Sample Solution

In [1]:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
In [2]:
de_lon, de_lat = np.loadtxt('data/germany.txt', unpack=True)
In [3]:
plt.figure(figsize=(6,7))
plt.plot(de_lon, de_lat)
Out[3]:
[<matplotlib.lines.Line2D at 0x117bbd320>]
In [4]:
import json
import requests

BASE_URL = 'http://api.openweathermap.org/data/2.5/weather'

def get_temperature(lon, lat):
    data = requests.get(BASE_URL, params={'lon': lon, 'lat':lat}).json()
    return data[u'main'][u'temp']
    
    
In [5]:
get_temperature(10, 52)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-5-db7f68cc12d0> in <module>()
----> 1 get_temperature(10, 52)

<ipython-input-4-70a2f60a8b1e> in get_temperature(lon, lat)
      6 def get_temperature(lon, lat):
      7     data = requests.get(BASE_URL, params={'lon': lon, 'lat':lat}).json()
----> 8     return data[u'main'][u'temp']
      9 
     10 

KeyError: 'main'
In [6]:
lon_all = np.linspace(4., 16., 10)
lat_all = np.linspace(47., 56., 10)

plt.figure(figsize=(6,7))
plt.plot(de_lon, de_lat, 'k')

for lon in lon_all:
    for lat in lat_all:
        temp = get_temperature(lon, lat) - 273.15
        plt.scatter(lon, lat, c=temp, s=100, vmin=-4., vmax=30.)
        
plt.colorbar()
plt.xlabel('Longitude')
plt.ylabel('Latitude')
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-6-a59052999c52> in <module>()
      7 for lon in lon_all:
      8     for lat in lat_all:
----> 9         temp = get_temperature(lon, lat) - 273.15
     10         plt.scatter(lon, lat, c=temp, s=100, vmin=-4., vmax=30.)
     11 

<ipython-input-4-70a2f60a8b1e> in get_temperature(lon, lat)
      6 def get_temperature(lon, lat):
      7     data = requests.get(BASE_URL, params={'lon': lon, 'lat':lat}).json()
----> 8     return data[u'main'][u'temp']
      9 
     10 

KeyError: 'main'