Skip to content

Commit

Permalink
Add my notebooks.
Browse files Browse the repository at this point in the history
  • Loading branch information
fperez committed Jan 30, 2012
1 parent 7e19e16 commit 5c42f98
Show file tree
Hide file tree
Showing 9 changed files with 2,219 additions and 0 deletions.
Binary file added data/dessert.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/stained_glass_barcelona.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/stinkbug.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
174 changes: 174 additions & 0 deletions image_tutorial.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
{
"metadata": {
"name": "image_tutorial"
},
"nbformat": 2,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"source": [
"# Matplotlib image tutorial",
"",
"This is a copy of the official [matplotlib introductory image tutorial](http://matplotlib.sourceforge.net/users/image_tutorial.html)",
"in the form of a notebook."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%pylab inline",
"import matplotlib.pyplot as plt",
"import matplotlib.image as mpimg",
"import numpy as np"
],
"language": "python",
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"img = mpimg.imread('data/stinkbug.png')"
],
"language": "python",
"outputs": [],
"prompt_number": 2
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"plt.imshow(img)"
],
"language": "python",
"outputs": [],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"lum_img = img[:,:,0]",
"fig, ax = plt.subplots()",
"imgplot = ax.imshow(lum_img)"
],
"language": "python",
"outputs": [],
"prompt_number": 4
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"imgplot.set_cmap('hot')",
"imgplot.figure"
],
"language": "python",
"outputs": [],
"prompt_number": 5
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"imgplot.set_cmap('spectral')",
"imgplot.figure"
],
"language": "python",
"outputs": [],
"prompt_number": 6
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"imgplot.set_cmap('spectral')",
"fig.colorbar(imgplot)",
"fig"
],
"language": "python",
"outputs": [],
"prompt_number": 7
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"plt.hist(lum_img.flatten(), 256, range=(0.0,1.0), fc='k', ec='k');"
],
"language": "python",
"outputs": [],
"prompt_number": 8
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,4))",
"",
"imgplot1 = ax1.imshow(lum_img)",
"ax1.set_title('Before')",
"fig.colorbar(imgplot1, ax=ax1, ticks=[0.1,0.3,0.5,0.7], orientation ='horizontal')",
"",
"imgplot2 = ax2.imshow(lum_img)",
"imgplot2.set_clim(0.0,0.7)",
"ax2.set_title('After')",
"fig.colorbar(imgplot2, ax=ax2, ticks=[0.1,0.3,0.5,0.7], orientation='horizontal');"
],
"language": "python",
"outputs": [],
"prompt_number": 9
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"import Image",
"img = Image.open('data/stinkbug.png') # Open image as PIL image object",
"rsize = img.resize((img.size[0]/10, img.size[1]/10)) # Use PIL to resize",
"rsizeArr = np.asarray(rsize) # Get array back"
],
"language": "python",
"outputs": [],
"prompt_number": 10
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"imgplot = plt.imshow(rsizeArr, interpolation='bilinear')"
],
"language": "python",
"outputs": [],
"prompt_number": 11
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"imgplot.set_interpolation('nearest')",
"imgplot.figure"
],
"language": "python",
"outputs": [],
"prompt_number": 12
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"imgplot.set_interpolation('bicubic')",
"imgplot.figure"
],
"language": "python",
"outputs": [],
"prompt_number": 13
}
]
}
]
}
186 changes: 186 additions & 0 deletions mapping_seismic_stations.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
{
"metadata": {
"name": "mapping_seismic_stations"
},
"nbformat": 2,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"source": [
"# Mapping seismic stations in the Himalayas with Numpy and Matplotlib",
"## Or reading datasets with custom dtypes and plotting Earth-based data with basemap"
]
},
{
"cell_type": "markdown",
"source": [
"In this exercise, we consider loading measurement files with the format:",
"",
"<pre>",
"# Station Lat Long Elev ",
"BIRA\t26.4840\t87.2670\t0.0120",
"BUNG\t27.8771\t85.8909\t1.1910",
"etc...",
"</pre>",
"",
"These are seismic measurement stations in the Himalaya, with the elevation indicated in km. Data with a structure such as this is common in many disciplines, and because we have a combination of text and numerical fields, we can't directly load it into a regular numpy array.",
"",
"But we can use numpy's ability to [define custom data types (dtypes)](http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html) to compactly describe our data in a single array, which we can then manipulate.",
"",
"If you have the basemap matplotlib toolkit installed, at the end of this example we will show a real Earth map and overlay the station locations on top of that.",
"",
"We start by configuring pylab support and loading the required modules."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%pylab inline"
],
"language": "python",
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"import numpy as np",
"import matplotlib.pyplot as plt"
],
"language": "python",
"outputs": [],
"prompt_number": 2
},
{
"cell_type": "markdown",
"source": [
"Now, we need to describe this dataset. There are several ways of declaring a dtype, in this simple case we show two equivalent ones. See the [numpy reference docs](http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html) for more details:"
]
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"# Data descriptor to make a proper array.",
"dt = [('station','S4'), ('lat',np.float32), ('lon',np.float32), ('elev',np.float32) ]",
"",
"# This is an alternate and fully equivalent form:",
"dt = dict(names = ('station','lat','lon','elev'),",
" formats = ('S4',np.float32,np.float32,np.float32) )"
],
"language": "python",
"outputs": [],
"prompt_number": 4
},
{
"cell_type": "markdown",
"source": [
"Now, we load the data using this dtype we've constructed, and view it as a recarray for convenient named-field access:"
]
},
{
"cell_type": "code",
"collapsed": true,
"input": [
"data_fname = os.path.join('data', 'stations.txt')",
"tab = np.loadtxt(data_fname, dt).view(np.recarray)"
],
"language": "python",
"outputs": [],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"ptitle = 'Seismic stations in the Himalaya'",
"print ptitle",
"print 'Stations:', tab.station",
"print 'Elevations (km):', tab.elev",
"print 'First station:', tab[0]",
"print 'Mean latitude:', tab.lat.mean()"
],
"language": "python",
"outputs": [],
"prompt_number": 4
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"f1, ax = plt.subplots(figsize = (8,5))",
"",
"# Make the size of the circles proportional to the elevation",
"sizes = 40*(tab.elev+1)",
"s = ax.scatter(tab.lon, tab.lat, s=sizes, c=tab.elev)",
"",
"# The colorbar must be associated with the return value of scatter()",
"f1.colorbar(s)",
"ax.set_title(ptitle)",
"# Now add text labels for all the stations. ",
"",
"# Note: when accessing single elements of the recarray, the named field",
"# syntax doesn't work and we must access the fields via ['name']",
"for record in tab:",
" ax.text(record['lon']+0.1, record['lat']+0.1, record['station'], weight='bold')"
],
"language": "python",
"outputs": [],
"prompt_number": 23
},
{
"cell_type": "markdown",
"source": [
"If we find the matplotlib basemap toolkit, we can show an even better plot by",
"overlaying the stations on top of a map of Earth at that location. But we",
"check this import so the code runs even without basemap."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"try:",
" from mpl_toolkits.basemap import Basemap",
"except ImportError:",
" pass",
"else:",
" # Draw the stations on a real map of the Earth.",
" # Find boundaries ",
" lon0 = 0.995*tab.lon.min()",
" lon1 = 1.01*tab.lon.max()",
" lat0 = 0.995*tab.lat.min()",
" lat1 = 1.01*tab.lat.max()",
" # Geographic grid to draw",
" parallels = np.linspace(lat0, lat1, 5)",
" meridians = np.linspace(lon0, lon1, 5)",
"",
" # Resolution of the basemap to load ('f' is *very* expensive)",
" resolution = 'i' # intermediate resolution for map info",
"",
" f2, ax2 = plt.subplots(figsize=(10,6))",
" m = Basemap(lon0, lat0, lon1, lat1, resolution=resolution, ax=ax2)",
" m.drawcountries(color=(1,1,0)) # country boundaries yellow",
" m.drawrivers(color=(0,1,1)) # rivers in cyan",
" m.bluemarble() # NASA bluemarble image",
" m.drawparallels(parallels, labels=[1,0,0,0], fmt='%.2f')",
" m.drawmeridians(meridians, labels=[0,0,0,1], fmt='%.2f')",
" s = m.scatter(tab.lon, tab.lat, s=sizes, c=tab.elev, zorder=10, alpha=0.6)",
" f2.colorbar(s)",
" ax2.set_title(ptitle)",
" for record in tab:",
" ax2.text( record['lon']+0.05, record['lat']+0.05, record['station'], ",
" weight='bold', color='yellow', zorder=10)"
],
"language": "python",
"outputs": [],
"prompt_number": 29
}
]
}
]
}
Loading

0 comments on commit 5c42f98

Please sign in to comment.