| |
- __builtin__.object
-
- Basemap
class Basemap(__builtin__.object) |
|
Set up a basemap with one of 18 supported map projections
(cylindrical equidistant, mercator, polyconic, oblique mercator,
transverse mercator, miller cylindrical, lambert conformal conic,
azimuthal equidistant, equidistant conic, lambert azimuthal equal area,
albers equal area conic, gnomonic, orthographic, sinusoidal, mollweide,
robinson, cassini-soldner or stereographic).
Doesn't actually draw anything, but sets up the map projection class and
creates the coastline, lake river and political boundary data
structures in native map projection coordinates.
Uses a pyrex interface to C-code from proj.4 (http://proj.maptools.org).
Useful instance variables:
projection - map projection ('cyl','merc','mill','lcc','eqdc','aea',
'laea', 'nplaea', 'splaea', 'tmerc', 'omerc', 'cass', 'gnom', 'poly',
'sinu', 'moll', 'ortho', 'robin', 'aeqd', 'npaeqd', 'spaeqd', 'stere',
'npstere' or 'spstere')
(projections prefixed with 'np' or 'sp' are special case polar-centric
versions of the parent projection)
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.
Example Usage:
>>> from matplotlib.toolkits.basemap import Basemap
>>> from pylab import *
>>> # 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".]
Contact: Jeff Whitaker <jeffrey.s.whitaker@noaa.gov> |
|
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, boundinglat=None, anchor='C', ax=None)
- create a Basemap instance.
arguments:
projection - map projection. 'cyl' - cylindrical equidistant, 'merc' -
mercator, 'lcc' - lambert conformal conic, 'stere' - stereographic,
'npstere' - stereographic, special case centered on north pole.
'spstere' - stereographic, special case centered on south pole,
'aea' - albers equal area conic, 'tmerc' - transverse mercator,
'aeqd' - azimuthal equidistant, 'mill' - miller cylindrical,
'npaeqd' - azimuthal equidistant, special case centered on north pole,
'spaeqd' - azimuthal equidistant, special case centered on south pole,
'eqdc' - equidistant conic, 'laea' - lambert azimuthal equal area,
'nplaea' - lambert azimuthal, special case centered on north pole,
'splaea' - lambert azimuthal, special case centered on south pole,
'cass' - cassini-soldner (transverse cylindrical equidistant),
'poly' - polyconic, 'omerc' - oblique mercator, 'ortho' - orthographic,
'sinu' - sinusoidal, 'moll' - mollweide, 'robin' - robinson,
and 'gnom' - gnomonic are currently available. Default 'cyl'.
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 'ortho', '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, either the lat/lon values of the corners or width and height must be
specified by the user.
resolution - resolution of boundary database to use. Can be 'c' (crude),
'l' (low), 'i' (intermediate), 'h' (high), or None. Default is 'c'.
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 for resolution
'c','l','i','h'.
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. Typically, you will
only want to override the default if you want to 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.
lat_ts - latitude of natural origin (used for mercator, and
optionally 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,
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.
- 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)
- 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)
- drawcountries(self, linewidth=0.5, color='k', antialiased=1, ax=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)
- drawgreatcircle(self, lon1, lat1, lon2, lat2, dtheta=0.02, **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.
dtheta - points on great circle computed every dtheta radians (default 0.02).
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.
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, ax=None)
- draw boundary around map projection region. If ax=None (default),
default axis instance is used, otherwise specified axis instance is used.
- drawmeridians(self, meridians, color='k', linewidth=1.0, linestyle='--', dashes=[1, 1], labels=[0, 0, 0, 0], 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.)
linestyle - line style for meridians (default '--', i.e. dashed).
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.
fmt is a format string to format the meridian labels (default '%g').
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, linestyle='--', dashes=[1, 1], labels=[0, 0, 0, 0], 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.)
linestyle - line style for parallels (default '--', i.e. dashed).
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.
fmt is a format string to format the parallel labels (default '%g').
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)
- 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)
- drawstates(self, linewidth=0.5, color='k', antialiased=1, ax=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)
- fillcontinents(self, color='0.8', ax=None)
- Fill continents.
color - color to fill continents (default gray).
ax - axes instance (overrides default axes instance)
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
Unlike pcolor, pcolormesh cannot handle masked arrays, and so
cannot be used to plot data when the grid lies partially outside
the projection limb (use pcolor or contourf instead).
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, 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)
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 and other attributes defined here:
- __dict__ = <dictproxy object>
- dictionary for instance variables (if defined)
- __weakref__ = <attribute '__weakref__' of 'Basemap' objects>
- list of weak references to the object (if defined)
| |