| |
- __builtin__.object
-
- Basemap
class Basemap(__builtin__.object) |
|
Class for plotting data on map projections with matplotlib.
See __init__ docstring for details on how to create a class
instance for a given map projection.
Useful instance variables:
projection - map projection. Print the module variable
"supported_projections" to see a list.
aspect - map aspect ratio (size of y dimension / size of x dimension).
llcrnrlon - longitude of lower left hand corner of the desired map domain.
llcrnrlon - latitude of lower left hand corner of the desired map domain.
urcrnrlon - longitude of upper right hand corner of the desired map domain.
urcrnrlon - latitude of upper right hand corner of the desired map domain.
llcrnrx,llcrnry,urcrnrx,urcrnry - corners of map domain in projection coordinates.
rmajor,rminor - equatorial and polar radii of ellipsoid used (in meters).
resolution - resolution of boundary dataset being used ('c' for crude,
'l' for low, etc.). If None, no boundary dataset is associated with the
Basemap instance.
srs - a string representing the 'spatial reference system' for the map
projection as defined by PROJ.4.
Example Usage:
>>> from matplotlib.toolkits.basemap import Basemap
>>> from pylab import load, meshgrid, title, arange, show
>>> # read in topo data (on a regular lat/lon grid)
>>> etopo = load('etopo20data.gz')
>>> lons = load('etopo20lons.gz')
>>> lats = load('etopo20lats.gz')
>>> # create Basemap instance for Robinson projection.
>>> m = Basemap(projection='robin',lon_0=0.5*(lons[0]+lons[-1]))
>>> # compute native map projection coordinates for lat/lon grid.
>>> x, y = m(*meshgrid(lons,lats))
>>> # make filled contour plot.
>>> cs = m.contourf(x,y,etopo,30,cmap=cm.jet)
>>> m.drawcoastlines() # draw coastlines
>>> m.drawmapboundary() # draw a line around the map region
>>> m.drawparallels(arange(-90.,120.,30.),labels=[1,0,0,0]) # draw parallels
>>> m.drawmeridians(arange(0.,420.,60.),labels=[0,0,0,1]) # draw meridians
>>> title('Robinson Projection') # add a title
>>> show()
[this example (simpletest.py) plus many others can be found in the
examples directory of source distribution. The "OO" version of this
example (which does not use pylab) is called "simpletest_oo.py".] |
|
Methods defined here:
- __call__(self, x, y, inverse=False)
- Calling a Basemap class instance with the arguments lon, lat will
convert lon/lat (in degrees) to x/y native map projection
coordinates (in meters). If optional keyword 'inverse' is
True (default is False), the inverse transformation from x/y
to lon/lat is performed.
For cylindrical equidistant projection ('cyl'), this
does nothing (i.e. x,y == lon,lat).
For non-cylindrical projections, the inverse transformation
always returns longitudes between -180 and 180 degrees. For
cylindrical projections (self.projection == 'cyl','mill' or 'merc')
the inverse transformation will return longitudes between
self.llcrnrlon and self.llcrnrlat.
input arguments lon, lat can be either scalar floats or N arrays.
- __init__(self, llcrnrlon=None, llcrnrlat=None, urcrnrlon=None, urcrnrlat=None, width=None, height=None, projection='cyl', resolution='c', area_thresh=None, rsphere=6370997.0, lat_ts=None, lat_1=None, lat_2=None, lat_0=None, lon_0=None, lon_1=None, lon_2=None, suppress_ticks=True, satellite_height=None, boundinglat=None, anchor='C', ax=None)
- create a Basemap instance.
This sets up a basemap with specified map projection.
and creates the coastline data structures in native map projection
coordinates.
arguments:
projection - map projection. Supported projections are:
'aeqd' = Azimuthal Equidistant
'poly' = Polyconic
'gnom' = Gnomonic
'moll' = Mollweide
'tmerc' = Transverse Mercator
'nplaea' = North-Polar Lambert Azimuthal
'mill' = Miller Cylindrical
'merc' = Mercator
'stere' = Stereographic
'npstere' = North-Polar Stereographic
'geos' = Geostationary
'laea' = Lambert Azimuthal Equal Area
'sinu' = Sinusoidal
'spstere' = South-Polar Stereographic
'lcc' = Lambert Conformal
'npaeqd' = North-Polar Azimuthal Equidistant
'eqdc' = Equidistant Conic
'cyl' = Cylindrical Equidistant
'omerc' = Oblique Mercator
'aea' = Albers Equal Area
'spaeqd' = South-Polar Azimuthal Equidistant
'ortho' = Orthographic
'cass' = Cassini-Soldner
'splaea' = South-Polar Lambert Azimuthal
'robin' = Robinson
Default is 'cyl'.
For most map projections, the map projection region can either be
specified by setting these keywords:
llcrnrlon - longitude of lower left hand corner of the desired map domain (degrees).
llcrnrlat - latitude of lower left hand corner of the desired map domain (degrees).
urcrnrlon - longitude of upper right hand corner of the desired map domain (degrees).
urcrnrlat - latitude of upper right hand corner of the desired map domain (degrees).
or these keywords:
width - width of desired map domain in projection coordinates (meters).
height - height of desired map domain in projection coordinates (meters).
lon_0 - center of desired map domain (in degrees).
lat_0 - center of desired map domain (in degrees).
For 'sinu', 'moll', 'npstere', 'spstere', 'nplaea', 'splaea', 'nplaea',
'splaea', 'npaeqd', 'spaeqd' or 'robin', the values of
llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat,width and height are ignored
(because either they are computed internally, or entire globe is
always plotted). For the cylindrical projections
('cyl','merc' and 'mill'), the default is to use
llcrnrlon=-180,llcrnrlat=-90, urcrnrlon=180 and urcrnrlat=90). For all other
projections except 'ortho' and 'geos', either the lat/lon values of the
corners or width and height must be specified by the user.
For 'ortho' and 'geos', the lat/lon values of the corners may be specified,
but if they are not, the entire globe is plotted.
resolution - resolution of boundary database to use. Can be 'c' (crude),
'l' (low), 'i' (intermediate), 'h' (high), 'f' (full) or None.
If None, no boundary data will be read in (and class methods
such as drawcoastlines will raise an exception if invoked).
Resolution drops off by roughly 80%
between datasets. Higher res datasets are much slower to draw.
Default 'c'. Coastline data is from the GSHHS
(http://www.soest.hawaii.edu/wessel/gshhs/gshhs.html).
State, country and river datasets from the Generic Mapping
Tools (http://gmt.soest.hawaii.edu).
area_thresh - coastline or lake with an area smaller than area_thresh
in km^2 will not be plotted. Default 10000,1000,100,10,1 for resolution
'c','l','i','h','f'.
rsphere - radius of the sphere used to define map projection (default
6370997 meters, close to the arithmetic mean radius of the earth). If
given as a sequence, the first two elements are interpreted as
the the radii of the major and minor axes of an ellipsoid. Note: sometimes
an ellipsoid is specified by the major axis and an 'inverse flattening
parameter' (if). The minor axis (b) can be computed from the major axis (a)
and the inverse flattening parameter using the formula if = a/(a-b).
suppress_ticks - suppress automatic drawing of axis ticks and labels
in map projection coordinates. Default False, so parallels and meridians
can be labelled instead. If parallel or meridian labelling is requested
(using drawparallels and drawmeridians methods), automatic tick labelling
will be supressed even is suppress_ticks=False. suppress_ticks=False
is useful if you want to use your own custom tick formatter, or
if you want to let matplotlib label the axes in meters
using native map projection coordinates
anchor - determines how map is placed in axes rectangle (passed to
axes.set_aspect). Default is 'C', which means map is centered.
Allowed values are ['C', 'SW', 'S', 'SE', 'E', 'NE', 'N', 'NW', 'W'].
ax - set default axes instance (default None - pylab.gca() may be used
to get the current axes instance). If you don't want pylab to be imported,
you can either set this to a pre-defined axes instance, or use the 'ax'
keyword in each Basemap method call that does drawing. In the first case,
all Basemap method calls will draw to the same axes instance. In the
second case, you can draw to different axes with the same Basemap instance.
You can also use the 'ax' keyword in individual method calls to
selectively override the default axes instance.
The following parameters are map projection parameters which all default to
None. Not all parameters are used by all projections, some are ignored.
The module variable 'projection_params' is a dictionary which
lists which parameters apply to which projections.
lat_ts - latitude of true scale for mercator projection, optional
for stereographic projection.
lat_1 - first standard parallel for lambert conformal, albers
equal area projection and equidistant conic projections. Latitude of one
of the two points on the projection centerline for oblique mercator.
If lat_1 is not given, but lat_0 is, lat_1 is set to lat_0 for
lambert conformal, albers equal area and equidistant conic.
lat_2 - second standard parallel for lambert conformal, albers
equal area projection and equidistant conic projections. Latitude of one
of the two points on the projection centerline for oblique mercator.
If lat_2 is not given, it is set to lat_1 for
lambert conformal, albers equal area and equidistant conic.
lon_1 - longitude of one of the two points on the projection centerline
for oblique mercator.
lon_2 - longitude of one of the two points on the projection centerline
for oblique mercator.
lat_0 - central latitude (y-axis origin) - used by all projections,
Must be equator for mercator projection.
lon_0 - central meridian (x-axis origin) - used by all projections,
boundinglat - bounding latitude for pole-centered projections (npstere,spstere,
nplaea,splaea,npaeqd,spaeqd). These projections are square regions centered
on the north or south pole. The longitude lon_0 is at 6-o'clock, and the
latitude circle boundinglat is tangent to the edge of the map at lon_0.
satellite_height - height of satellite (in m) above equator -
only relevant for geostationary projections ('geos').
Here are the most commonly used class methods (see the docstring
for each for more details):
To draw a graticule grid (labelled latitude and longitude lines)
use the drawparallels and drawmeridians methods.
To draw coastline, rivers and political boundaries, use the
the drawcontinents, drawrivers, drawcountries and drawstates methods.
To fill the continents and inland lakes, use the fillcontinents method.
To draw the boundary of the map projection region, and fill the
interior a certain color, use the drawmapboundary method.
The contour, contourf, pcolor, pcolormesh, plot, scatter
quiver and imshow methods use the corresponding matplotlib axes
methods to draw on the map.
The transform_scalar method can be used to interpolate regular
lat/lon grids of scalar data to native map projection grids.
The transform_vector method can be used to interpolate and rotate
regular lat/lon grids of vector data to native map projection grids.
The rotate_vector method rotates a vector field from lat/lon
coordinates into map projections coordinates, without doing any
interpolation.
The readshapefile method can be used to read in data from ESRI
shapefiles.
The drawgreatcircle method draws great circles on the map.
- contour(self, x, y, data, *args, **kwargs)
- Make a contour plot over the map (see pylab.contour documentation).
extra keyword 'ax' can be used to override the default axis instance.
- contourf(self, x, y, data, *args, **kwargs)
- Make a filled contour plot over the map (see pylab.contourf documentation).
If x or y are outside projection limb (i.e. they have values > 1.e20),
the corresponing data elements will be masked.
Extra keyword 'ax' can be used to override the default axis instance.
- drawcoastlines(self, linewidth=1.0, color='k', antialiased=1, ax=None, zorder=None)
- Draw coastlines.
linewidth - coastline width (default 1.)
color - coastline color (default black)
antialiased - antialiasing switch for coastlines (default True).
ax - axes instance (overrides default axes instance)
zorder - sets the zorder for the coastlines (if not specified,
uses default zorder for LineCollections).
- drawcountries(self, linewidth=0.5, color='k', antialiased=1, ax=None, zorder=None)
- Draw country boundaries.
linewidth - country boundary line width (default 0.5)
color - country boundary line color (default black)
antialiased - antialiasing switch for country boundaries (default True).
ax - axes instance (overrides default axes instance)
zorder - sets the zorder for the country boundaries (if not specified,
uses default zorder for LineCollections).
- drawgreatcircle(self, lon1, lat1, lon2, lat2, del_s=100.0, **kwargs)
- draw a great circle on the map.
lon1,lat1 - longitude,latitude of one endpoint of the great circle.
lon2,lat2 - longitude,latitude of the other endpoint of the great circle.
del_s - points on great circle computed every delta kilometers (default 100).
Other keyword arguments (**kwargs) control plotting of great circle line,
see pylab.plot documentation for details.
Note: cannot handle situations in which the great circle intersects
the edge of the map projection domain, and then re-enters the domain.
- drawlsmask(self, rgba_land, rgba_ocean, lsmask=None, lsmask_lons=None, lsmask_lats=None, lakes=False, **kwargs)
- draw land-sea mask image.
*Note* the land-sea mask image cannot be overlaid on top
of other images, due to limitations in matplotlib image handling.
land is colored with rgba integer tuple rgba_land.
ocean is colored with rgba integer tuple rgba_ocean.
For example, to color oceans blue and land green, use
rgba_ocean = (0,0,255,255) and rgba_land = (0,255,0,255).
To make oceans transparent (useful if you just want to mask land
regions over another image), use rgba_ocean = (0,0,255,0).
If lakes=True, inland lakes are also colored with
rgba_ocean (default is lakes=False).
Default land-sea mask is from
http://www.ngdc.noaa.gov/seg/cdroms/graham/graham/graham.htm
and has 5-minute resolution.
To specify your own global land-sea mask, set the
lsmask keyword to a (nlats, nlons) array
with 0's for ocean pixels, 1's for land pixels and
optionally 2's for inland lake pixels.
The lsmask_lons keyword should be a 1-d array
with the longitudes of the mask, lsmask_lats should be
a 1-d array with the latitudes. Longitudes should be ordered
from -180 W eastward, latitudes from -90 S northward.
If any of the lsmask, lsmask_lons or lsmask_lats keywords are not
set, the default land-sea mask is used.
extra keyword 'ax' can be used to override the default axis instance.
- drawmapboundary(self, color='k', linewidth=1.0, fill_color=None, zorder=None, ax=None)
- draw boundary around map projection region, optionally
filling interior of region.
linewidth - line width for boundary (default 1.)
color - color of boundary line (default black)
fill_color - fill the map region background with this
color (default is no fill or fill with axis background color).
zorder - sets the zorder for filling map background
(default 0).
ax - axes instance to use (default None, use default axes
instance).
- drawmeridians(self, meridians, color='k', linewidth=1.0, zorder=None, dashes=[1, 1], labels=[0, 0, 0, 0], labelstyle=None, fmt='%g', xoffset=None, yoffset=None, ax=None, **kwargs)
- draw meridians (longitude lines).
meridians - list containing longitude values to draw (in degrees).
color - color to draw meridians (default black).
linewidth - line width for meridians (default 1.)
zorder - sets the zorder for meridians (if not specified,
uses default zorder for Line2D class).
dashes - dash pattern for meridians (default [1,1], i.e. 1 pixel on,
1 pixel off).
labels - list of 4 values (default [0,0,0,0]) that control whether
meridians are labelled where they intersect the left, right, top or
bottom of the plot. For example labels=[1,0,0,1] will cause meridians
to be labelled where they intersect the left and bottom of the plot,
but not the right and top.
labelstyle - if set to "+/-", east and west longitudes are labelled
with "+" and "-", otherwise they are labelled with "E" and "W".
fmt can be is a format string to format the meridian labels
(default '%g') or a function that takes a longitude value
in degrees as it's only argument and returns a formatted string.
xoffset - label offset from edge of map in x-direction
(default is 0.01 times width of map in map projection coordinates).
yoffset - label offset from edge of map in y-direction
(default is 0.01 times height of map in map projection coordinates).
ax - axes instance (overrides default axes instance)
additional keyword arguments control text properties for labels (see
pylab.text documentation)
- drawparallels(self, circles, color='k', linewidth=1.0, zorder=None, dashes=[1, 1], labels=[0, 0, 0, 0], labelstyle=None, fmt='%g', xoffset=None, yoffset=None, ax=None, **kwargs)
- draw parallels (latitude lines).
circles - list containing latitude values to draw (in degrees).
color - color to draw parallels (default black).
linewidth - line width for parallels (default 1.)
zorder - sets the zorder for parallels (if not specified,
uses default zorder for Line2D class).
dashes - dash pattern for parallels (default [1,1], i.e. 1 pixel on,
1 pixel off).
labels - list of 4 values (default [0,0,0,0]) that control whether
parallels are labelled where they intersect the left, right, top or
bottom of the plot. For example labels=[1,0,0,1] will cause parallels
to be labelled where they intersect the left and bottom of the plot,
but not the right and top.
labelstyle - if set to "+/-", north and south latitudes are labelled
with "+" and "-", otherwise they are labelled with "N" and "S".
fmt can be is a format string to format the parallel labels
(default '%g') or a function that takes a latitude value
in degrees as it's only argument and returns a formatted string.
xoffset - label offset from edge of map in x-direction
(default is 0.01 times width of map in map projection coordinates).
yoffset - label offset from edge of map in y-direction
(default is 0.01 times height of map in map projection coordinates).
ax - axes instance (overrides default axes instance)
additional keyword arguments control text properties for labels (see
pylab.text documentation)
- drawrivers(self, linewidth=0.5, color='k', antialiased=1, ax=None, zorder=None)
- Draw major rivers.
linewidth - river boundary line width (default 0.5)
color - river boundary line color (default black)
antialiased - antialiasing switch for river boundaries (default True).
ax - axes instance (overrides default axes instance)
zorder - sets the zorder for the rivers (if not specified,
uses default zorder for LineCollections).
- drawstates(self, linewidth=0.5, color='k', antialiased=1, ax=None, zorder=None)
- Draw state boundaries in Americas.
linewidth - state boundary line width (default 0.5)
color - state boundary line color (default black)
antialiased - antialiasing switch for state boundaries (default True).
ax - axes instance (overrides default axes instance)
zorder - sets the zorder for the state boundaries (if not specified,
uses default zorder for LineCollections).
- fillcontinents(self, color='0.8', lake_color=None, ax=None, zorder=None)
- Fill continents.
color - color to fill continents (default gray).
lake_color - color to fill inland lakes (default axes background).
ax - axes instance (overrides default axes instance).
zorder - sets the zorder for the continent polygons (if not specified,
uses default zorder for a Polygon patch). Set to zero if you want to paint
over the filled continents).
After filling continents, lakes are re-filled with axis background color.
- gcpoints(self, lon1, lat1, lon2, lat2, npoints)
- compute npoints points along a great circle with endpoints
(lon1,lat1) and (lon2,lat2). Returns arrays x,y
with map projection coordinates.
- imshow(self, *args, **kwargs)
- Display an image over the map (see pylab.imshow documentation).
extent and origin keywords set automatically so image will be drawn
over map region.
extra keyword 'ax' can be used to override the default axis instance.
- makegrid(self, nx, ny, returnxy=False)
- return arrays of shape (ny,nx) containing lon,lat coordinates of
an equally spaced native projection grid.
if returnxy = True, the x,y values of the grid are returned also.
- pcolor(self, x, y, data, **kwargs)
- Make a pseudo-color plot over the map.
see pylab.pcolor documentation for definition of **kwargs
If x or y are outside projection limb (i.e. they have values > 1.e20)
they will be convert to masked arrays with those values masked.
As a result, those values will not be plotted.
extra keyword 'ax' can be used to override the default axis instance.
- pcolormesh(self, x, y, data, **kwargs)
- Make a pseudo-color plot over the map.
see pylab.pcolormesh documentation for definition of **kwargs
extra keyword 'ax' can be used to override the default axis instance.
- plot(self, *args, **kwargs)
- Draw lines and/or markers on the map (see pylab.plot documentation).
extra keyword 'ax' can be used to override the default axis instance.
- quiver(self, x, y, u, v, *args, **kwargs)
- Make a vector plot (u, v) with arrows on the map.
Extra arguments (*args and **kwargs) passed to quiver Axes method (see
pylab.quiver documentation for details).
extra keyword 'ax' can be used to override the default axis instance.
- readshapefile(self, shapefile, name, drawbounds=True, zorder=None, linewidth=0.5, color='k', antialiased=1, ax=None)
- read in shape file, draw boundaries on map.
Restrictions:
- Assumes shapes are 2D
- vertices must be in geographic (lat/lon) coordinates.
shapefile - path to shapefile components. Example:
shapefile='/home/jeff/esri/world_borders' assumes that
world_borders.shp, world_borders.shx and world_borders.dbf
live in /home/jeff/esri.
name - name for Basemap attribute to hold the shapefile
vertices in native map projection coordinates.
Class attribute name+'_info' is a list of dictionaries, one
for each shape, containing attributes of each shape from dbf file.
For example, if name='counties', self.counties
will be a list of vertices for each shape in map projection
coordinates and self.counties_info will be a list of dictionaries
with shape attributes. Rings in individual shapes are split out
into separate polygons. Additional keys
'RINGNUM' and 'SHAPENUM' are added to shape attribute dictionary.
drawbounds - draw boundaries of shapes (default True)
zorder = shape boundary zorder (if not specified, default for LineCollection
is used).
linewidth - shape boundary line width (default 0.5)
color - shape boundary line color (default black)
antialiased - antialiasing switch for shape boundaries (default True).
ax - axes instance (overrides default axes instance)
returns a tuple (num_shapes, type, min, max) containing shape file info.
num_shapes is the number of shapes, type is the type code (one of
the SHPT* constants defined in the shapelib module, see
http://shapelib.maptools.org/shp_api.html) and min and
max are 4-element lists with the minimum and maximum values of the
vertices.
- rotate_vector(self, uin, vin, lons, lats, returnxy=False)
- rotate a vector field (uin,vin) on a rectilinear lat/lon grid
with longitudes = lons and latitudes = lats from geographical into map
projection coordinates.
Differs from transform_vector in that no interpolation is done,
the vector is returned on the same lat/lon grid, but rotated into
x,y coordinates.
lons, lats must be rank-2 arrays containing longitudes and latitudes
(in degrees) of grid.
if returnxy=True, the x and y values of the lat/lon grid
are also returned (default False).
The input vector field is defined in spherical coordinates (it
has eastward and northward components) while the output
vector field is rotated to map projection coordinates (relative
to x and y). The magnitude of the vector is preserved.
- scatter(self, *args, **kwargs)
- Plot points with markers on the map (see pylab.scatter documentation).
extra keyword 'ax' can be used to override the default axes instance.
- set_axes_limits(self, ax=None)
- Set axis limits, fix aspect ratio for map domain using current
or specified axes instance.
- transform_scalar(self, datin, lons, lats, nx, ny, returnxy=False, checkbounds=False, order=1, masked=False)
- interpolate a scalar field (datin) from a lat/lon grid with longitudes =
lons and latitudes = lats to a (ny,nx) native map projection grid.
Typically used to transform data to map projection coordinates
so it can be plotted on the map with imshow.
lons, lats must be rank-1 arrays containing longitudes and latitudes
(in degrees) of datin grid in increasing order
(i.e. from dateline eastward, and South Pole northward).
For non-cylindrical projections (those other than
cylindrical equidistant, mercator and miller)
lons must fit within range -180 to 180.
if returnxy=True, the x and y values of the native map projection grid
are also returned.
If checkbounds=True, values of lons and lats are checked to see that
they lie within the map projection region. Default is False.
If checkbounds=False, points outside map projection region will
be clipped to values on the boundary if masked=False. If masked=True,
the return value will be a masked array with those points masked.
The order keyword can be 0 for nearest-neighbor interpolation,
or 1 for bilinear interpolation (default 1).
- transform_vector(self, uin, vin, lons, lats, nx, ny, returnxy=False, checkbounds=False, order=1, masked=False)
- rotate and interpolate a vector field (uin,vin) from a lat/lon grid
with longitudes = lons and latitudes = lats to a
(ny,nx) native map projection grid.
lons, lats must be rank-1 arrays containing longitudes and latitudes
(in degrees) of datin grid in increasing order
(i.e. from dateline eastward, and South Pole northward).
For non-cylindrical projections (those other than
cylindrical equidistant, mercator and miller)
lons must fit within range -180 to 180.
The input vector field is defined in spherical coordinates (it
has eastward and northward components) while the output
vector field is rotated to map projection coordinates (relative
to x and y). The magnitude of the vector is preserved.
if returnxy=True, the x and y values of the native map projection grid
are also returned (default False).
If checkbounds=True, values of lons and lats are checked to see that
they lie within the map projection region. Default is False.
If checkbounds=False, points outside map projection region will
be clipped to values on the boundary if masked=False. If masked=True,
the return value will be a masked array with those points masked.
The order keyword can be 0 for nearest-neighbor interpolation,
or 1 for bilinear interpolation (default 1).
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
| |