<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Graphs and maps (Matplotlib and Basemap)
Nikolay Koldunov
koldunovn@gmail.com
This is part of Python for Geosciences notes.
=============
Matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.
Usually we import matplotlib as follows
Step1:  This allows inline graphics in IPython (Jupyter) notebooks and imports functions nessesary for ploting as plt. In addition we import numpy as np.
Let's prepare some data
Step2:  Plot is as easy as this
Step3:  Line style and labels are controlled in a way similar to Matlab
Step4:  You can plot several individual lines at once
Step5:  One more example
Step6:  If you feel a bit playful (only in matplotlib > 1.3)
Step7:  Following example is from matplotlib - 2D and 3D plotting in Python - great place to start for people interested in matplotlib.
Step8:  When you going to plot something more or less complicated in Matplotlib, the first thing you do is open the Matplotlib example gallery and choose example closest to your case.
You can directly load python code (or basically any text file) to the notebook. This time we download code from the Matplotlib example gallery
Step9:  Maps ... using Basemap
In order to create a map we have to first import some data. We are going to use NCEP reanalysis file from previous section
Step10:  Here we create netCDF variable objec for air (we would like to have acces to some of the attributes), but from lat and lon we import only data valies
Step11:  Easiest way to look at the array is imshow
Step12:  But we want some real map 
Step13:  Our coordinate variables are vectors
Step14:  For the map we need 2d coordinate arrays. Convert lot lan to 2d
Step15:  Import Basemap - library for plotting 2D data on maps
Step16:  Create Basemap instance (with certain characteristics) and convert lon lat to map coordinates
Step17:  Creating the map now is only two lines
Step18:  We can make the map look prettier by adding couple of lines
Step19:  You can change map characteristics by changin the Basemap instance
Step20:  While the rest of the code might be the same
Step21:  One more map exampe
<ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pylab as plt
import numpy as np
Explanation: Graphs and maps (Matplotlib and Basemap)
Nikolay Koldunov
koldunovn@gmail.com
This is part of Python for Geosciences notes.
=============
Matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.
Usually we import matplotlib as follows:
End of explanation
x = np.linspace(0,10,20)
y = x ** 2
Explanation: This allows inline graphics in IPython (Jupyter) notebooks and imports functions nessesary for ploting as plt. In addition we import numpy as np.
Let's prepare some data:
End of explanation
plt.plot(x,y);
Explanation: Plot is as easy as this:
End of explanation
plt.plot(x, y, 'r--o')
plt.xlabel('x')
plt.ylabel('y')
plt.title('title');
Explanation: Line style and labels are controlled in a way similar to Matlab:
End of explanation
plt.plot(x, y, 'r--o', x, y ** 1.1, 'bs', x, y ** 1.2, 'g^-' );
Explanation: You can plot several individual lines at once:
End of explanation
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
Explanation: One more example:
End of explanation
with plt.xkcd():
    x = np.linspace(0, 1)
    y = np.sin(4 * np.pi * x) * np.exp(-5 * x)
    plt.fill(x, y, 'r')
    plt.grid(False)
Explanation: If you feel a bit playful (only in matplotlib > 1.3):
End of explanation
n = np.array([0,1,2,3,4,5])
xx = np.linspace(-0.75, 1., 100)
x = np.linspace(0, 5, 10)
fig, axes = plt.subplots(1, 4, figsize=(12,3))
axes[0].scatter(xx, xx + 0.25*np.random.randn(len(xx)))
axes[1].step(n, n**2, lw=2)
axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)
axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5);
Explanation: Following example is from matplotlib - 2D and 3D plotting in Python - great place to start for people interested in matplotlib.
End of explanation
# %load http://matplotlib.org/mpl_examples/pylab_examples/griddata_demo.py
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import numpy as np
# make up data.
#npts = int(raw_input('enter # of random points to plot:'))
seed(0)
npts = 200
x = uniform(-2, 2, npts)
y = uniform(-2, 2, npts)
z = x*np.exp(-x**2 - y**2)
# define grid.
xi = np.linspace(-2.1, 2.1, 100)
yi = np.linspace(-2.1, 2.1, 200)
# grid the data.
zi = griddata(x, y, z, xi, yi, interp='linear')
# contour the gridded data, plotting dots at the nonuniform data points.
CS = plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k')
CS = plt.contourf(xi, yi, zi, 15, cmap=plt.cm.rainbow,
                  vmax=abs(zi).max(), vmin=-abs(zi).max())
plt.colorbar()  # draw colorbar
# plot data points.
plt.scatter(x, y, marker='o', c='b', s=5, zorder=10)
plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.title('griddata test (%d points)' % npts)
plt.show()
Explanation: When you going to plot something more or less complicated in Matplotlib, the first thing you do is open the Matplotlib example gallery and choose example closest to your case.
You can directly load python code (or basically any text file) to the notebook. This time we download code from the Matplotlib example gallery:
End of explanation
from netCDF4 import Dataset
f =Dataset('air.sig995.2012.nc')
Explanation: Maps ... using Basemap
In order to create a map we have to first import some data. We are going to use NCEP reanalysis file from previous section:
End of explanation
air = f.variables['air']
lat = f.variables['lat'][:]
lon = f.variables['lon'][:]
Explanation: Here we create netCDF variable objec for air (we would like to have acces to some of the attributes), but from lat and lon we import only data valies:
End of explanation
plt.imshow(air[0,:,:])
plt.colorbar();
Explanation: Easiest way to look at the array is imshow:
End of explanation
air_c = air[:]  - 273.15
Explanation: But we want some real map :) First convert data from air:
End of explanation
lat.shape
Explanation: Our coordinate variables are vectors:
End of explanation
lon2, lat2 = np.meshgrid(lon,lat)
Explanation: For the map we need 2d coordinate arrays. Convert lot lan to 2d:
End of explanation
from mpl_toolkits.basemap import Basemap
Explanation: Import Basemap - library for plotting 2D data on maps:
End of explanation
m = Basemap(projection='npstere',boundinglat=60,lon_0=0,resolution='l')
x, y = m(lon2, lat2)
Explanation: Create Basemap instance (with certain characteristics) and convert lon lat to map coordinates
End of explanation
m.drawcoastlines()
m.contourf(x,y,air_c[0,:,:])
Explanation: Creating the map now is only two lines:
End of explanation
fig = plt.figure(figsize=(15,7))
m.fillcontinents(color='gray',lake_color='gray')
m.drawcoastlines()
m.drawparallels(np.arange(-80.,81.,20.))
m.drawmeridians(np.arange(-180.,181.,20.))
m.drawmapboundary(fill_color='white')
m.contourf(x,y,air_c[0,:,:],40)
plt.title('Monthly mean SAT')
plt.colorbar()
Explanation: We can make the map look prettier by adding couple of lines:
End of explanation
m = Basemap(projection='ortho',lat_0=45,lon_0=-100,resolution='l')
x, y = m(lon2, lat2)
Explanation: You can change map characteristics by changin the Basemap instance:
End of explanation
fig = plt.figure(figsize=(15,7))
#m.fillcontinents(color='gray',lake_color='gray')
m.drawcoastlines()
m.drawparallels(np.arange(-80.,81.,20.))
m.drawmeridians(np.arange(-180.,181.,20.))
m.drawmapboundary(fill_color='white')
cs = m.contourf(x,y,air_c[0,:,:],20)
plt.title('Monthly mean SAT')
Explanation: While the rest of the code might be the same:
End of explanation
m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
            llcrnrlon=0,urcrnrlon=360,resolution='c')
x, y = m(lon2, lat2)
fig = plt.figure(figsize=(15,7))
#m.fillcontinents(color='gray',lake_color='gray')
m.drawcoastlines()
m.drawparallels(np.arange(-80.,81.,20.))
m.drawmeridians(np.arange(0.,360.,20.))
m.drawmapboundary(fill_color='white')
cs = m.contourf(x,y,air[0,:,:],20)
plt.title('Monthly mean SAT')
Explanation: One more map exampe:
End of explanation
<END_TASK>