Module for plotting data on maps with matplotlib.
Contains the Basemap class (which does most of the heavy lifting), and the following functions:
NetCDFFile(): Read local and remote NetCDF datasets.
interp(): bilinear interpolation between rectilinear grids.
maskoceans(): mask ‘wet’ points of an input array.
shiftgrid(): shifts global lat/lon grids east or west.
addcyclic(): Add cyclic (wraparound) point in longitude.
num2date(): convert from a numeric time value to a datetime object.
date2num(): convert from a datetime object to a numeric time value.
date2index(): compute a time variable index corresponding to a date.
Sets up a basemap with specified map projection. and creates the coastline data structures in map projection coordinates.
Calling a Basemap class instance with the arguments lon, lat will convert lon/lat (in degrees) to x/y map projection coordinates (in meters). The inverse transformation is done if the optional keyword inverse is set to True.
The desired projection is set with the projection keyword. Default is cyl. Supported values for the projection keyword are:
| Value | Description |
|---|---|
| aeqd | Azimuthal Equidistant |
| poly | Polyconic |
| gnom | Gnomonic |
| moll | Mollweide |
| tmerc | Transverse Mercator |
| nplaea | North-Polar Lambert Azimuthal |
| gall | Gall Stereographic Cylindrical |
| mill | Miller Cylindrical |
| merc | Mercator |
| stere | Stereographic |
| npstere | North-Polar Stereographic |
| geos | Geostationary |
| vandg | van der Grinten |
| laea | Lambert Azimuthal Equal Area |
| mbtfpq | McBryde-Thomas Flat-Polar Quartic |
| 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 |
For most map projections, the map projection region can either be specified by setting these keywords:
| Keyword | Description |
|---|---|
| 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
| Keyword | Description |
|---|---|
| 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, npaeqd, spaeqd, robin or mbtfpq, 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, mill and gall), 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, or the x/y values of the corners (llcrnrx,llcrnry,urcrnrx,urcrnry) in the coordinate system of the global projection (with x=0,y=0 at the center of the global projection). If the corners are not specified, the entire globe is plotted.
Other keyword arguments:
| Keyword | Description |
|---|---|
| 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 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 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 if 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 map projection coordinates. |
| fix_aspect | fix aspect ratio of plot to match aspect ratio of map projection region (default True). |
| 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, and W. |
| ax | set default axes instance (default None - matplotlib.pyplot.gca() may be used to get the current axes instance). If you don``t want matplotlib.pyplot 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 keywords 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.
| Keyword | Description |
|---|---|
| lat_ts | latitude of true scale. Optional for stereographic and mercator projections. default is lat_0 for stereographic projection. default is 0 for mercator projection. |
| lat_1 | first standard parallel for lambert conformal, albers equal area and equidistant conic. 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 and equidistant conic. 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. |
| no_rot | only used by oblique mercator. If set to True, the map projection coordinates will not be rotated to true North. Default is False (projection coordinates are automatically rotated). |
| 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. |
| satellite_height | height of satellite (in m) above equator - only relevant for geostationary projections (geos). Default 35,786 km. |
Useful instance variables:
| Variable Name | Description |
|---|---|
| projection | map projection. Print the module variable supported_projections to see a list of allowed values. |
| aspect | map aspect ratio (size of y dimension / size of x dimension). |
| llcrnrlon | longitude of lower left hand corner of the selected map domain. |
| llcrnrlat | latitude of lower left hand corner of the selected map domain. |
| urcrnrlon | longitude of upper right hand corner of the selected map domain. |
| urcrnrlat | latitude of upper right hand corner of the selected map domain. |
| llcrnrx | x value of lower left hand corner of the selected map domain in map projection coordinates. |
| llcrnry | y value of lower left hand corner of the selected map domain in map projection coordinates. |
| urcrnrx | x value of upper right hand corner of the selected map domain in map projection coordinates. |
| urcrnry | y value of upper right hand corner of the selected map domain in map projection coordinates. |
| rmajor | equatorial radius of ellipsoid used (in meters). |
| rminor | polar radius 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. |
| proj4string | the string describing the map projection that is used by PROJ.4. |
Converting from Geographic (lon/lat) to Map Projection (x/y) Coordinates
Calling a Basemap class instance with the arguments lon, lat will convert lon/lat (in degrees) to x/y 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, gall or merc) the inverse transformation will return longitudes between self.llcrnrlon and self.llcrnrlat.
Input arguments lon, lat can be either scalar floats, sequences or numpy arrays.
Example Usage:
>>> from mpl_toolkits.basemap import Basemap
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> # read in topo data (on a regular lat/lon grid)
>>> etopo = np.loadtxt('etopo20data.gz')
>>> lons = np.loadtxt('etopo20lons.gz')
>>> lats = np.loadtxt('etopo20lats.gz')
>>> # create Basemap instance for Robinson projection.
>>> m = Basemap(projection='robin',lon_0=0.5*(lons[0]+lons[-1]))
>>> # compute map projection coordinates for lat/lon grid.
>>> x, y = m(*np.meshgrid(lons,lats))
>>> # make filled contour plot.
>>> cs = m.contourf(x,y,etopo,30,cmap=plt.cm.jet)
>>> m.drawcoastlines() # draw coastlines
>>> m.drawmapboundary() # draw a line around the map region
>>> m.drawparallels(np.arange(-90.,120.,30.),labels=[1,0,0,0]) # draw parallels
>>> m.drawmeridians(np.arange(0.,420.,60.),labels=[0,0,0,1]) # draw meridians
>>> plt.title('Robinson Projection') # add a title
>>> plt.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 matplotlib.pyplot) is called “simpletest_oo.py”.]
Make a wind barb plot (u, v) with on the map. (see matplotlib.pyplot.barbs documentation).
Extra keyword ax can be used to override the default axis instance.
Other *args and **kwargs passed on to matplotlib.pyplot.barbs
Returns two matplotlib.axes.Barbs instances, one for the Northern Hemisphere and one for the Southern Hemisphere.
display blue marble image (from http://visibleearth.nasa.gov) as map background. Default image size is 5400x2700, which can be quite slow and use quite a bit of memory. The scale keyword can be used to downsample the image (scale=0.5 downsamples to 2700x1350).
**kwargs passed on to imshow().
returns a matplotlib.image.AxesImage instance.
Make a contour plot over the map (see matplotlib.pyplot.contour documentation).
Extra keyword ax can be used to override the default axis instance.
Other *args and **kwargs passed on to matplotlib.pyplot.contour.
Make a filled contour plot over the map (see matplotlib.pyplot.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.
Other *args and **kwargs passed on to matplotlib.pyplot.scatter.
Draw coastlines.
| Keyword | Description |
|---|---|
| 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 matplotlib.patches.LineCollections). |
returns a matplotlib.patches.LineCollection object.
Draw country boundaries.
| Keyword | Description |
|---|---|
| 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 matplotlib.patches.LineCollections). |
returns a matplotlib.patches.LineCollection object.
Draw a great circle on the map from the longitude-latitude pair lon1,lat1 to lon2,lat2
| Keyword | Description |
|---|---|
| del_s | points on great circle computed every del_s kilometers (default 100). |
| **kwargs | other keyword arguments are passed on to plot() method of Basemap instance. |
Note
Cannot handle situations in which the great circle intersects the edge of the map projection domain, and then re-enters the domain.
Returns a matplotlib.lines.Line2D object.
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 (you can’t specify the zorder of an image).
| Keywords | Description |
|---|---|
| land_color | desired land color (color name or rgba tuple). Default gray (“0.8”). |
| ocean_color | desired ocean color (color name or rgba tuple). Default white. |
| lakes | If True, inland lakes are also colored with ocean_color (default is lakes=False). |
| lsmask | An array of 0’s for ocean pixels, 1’s for land pixels and optionally 2’s for inland lake pixels defining a global land-sea mask. Default is None, and default 5-minute resolution land-sea mask is used. |
| lsmask_lons | 1d array of longitudes for lsmask (ignored if lsmask is None). Longitudes must be ordered from -180 W eastward. |
| lsmask_lats | 1d array of latitudes for lsmask (ignored if lsmask is None). Latitudes must be ordered from -90 S northward. |
| **kwargs | extra keyword arguments passed on to imshow() |
If any of the lsmask, lsmask_lons or lsmask_lats keywords are not set, the default land-sea mask from http://www.ngdc.noaa.gov/ecosys/cdroms/graham/graham/graham.htm. is used.
Extra keyword ax can be used to override the default axis instance.
returns a matplotlib.image.AxesImage instance.
draw boundary around map projection region, optionally filling interior of region.
| Keyword | Description |
|---|---|
| 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). |
returns matplotlib.collections.PatchCollection representing map boundary.
Draw a map scale at lon,lat of length length representing distance in the map projection coordinates at lon0,lat0.
| Keywords | Description |
|---|---|
| units | the units of the length argument (Default km). |
| barstyle | simple or fancy (roughly corresponding to the styles provided by Generic Mapping Tools). Default simple. |
| fontsize | for map scale annotations, default 9. |
| color | for map scale annotations, default black. |
| labelstype | simple (default) or fancy. For fancy the map scale factor (ratio betwee the actual distance and map projection distance at lon0,lat0) and the value of lon0,lat0 are also displayed on the top of the scale bar. For simple, just the units are display on top and the distance below the scale bar. |
| yoffset | yoffset controls how tall the scale bar is, and how far the annotations are offset from the scale bar. Default is 0.02 times the height of the map (0.02*(self.ymax-self.ymin)). |
| fillcolor1(2) | colors of the alternating filled regions (default white and black). Only relevant for ‘fancy’ barstyle. |
Extra keyword ax can be used to override the default axis instance.
Draw and label meridians (longitude lines) for values (in degrees) given in the sequence meridians.
| Keyword | Description |
|---|---|
| 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 matplotlib.lines.Line2D objects). |
| 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 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 | 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) |
| latmax | absolute value of latitude to which meridians are drawn (default is 80). |
| **kwargs | additional keyword arguments controlling text for labels that are passed on to the text method of the axes instance (see matplotlib.pyplot.text documentation). |
returns a dictionary whose keys are the meridian values, and whose values are tuples containing lists of the matplotlib.lines.Line2D and matplotlib.text.Text instances associated with each meridian.
Draw and label parallels (latitude lines) for values (in degrees) given in the sequence circles.
| Keyword | Description |
|---|---|
| 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 matplotlib.lines.Line2D objects). |
| 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 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 | 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) |
| latmax | absolute value of latitude to which meridians are drawn (default is 80). |
| **kwargs | additional keyword arguments controlling text for labels that are passed on to the text method of the axes instance (see matplotlib.pyplot.text documentation). |
returns a dictionary whose keys are the parallel values, and whose values are tuples containing lists of the matplotlib.lines.Line2D and matplotlib.text.Text instances associated with each parallel.
Draw major rivers.
| Keyword | Description |
|---|---|
| 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 matplotlib.patches.LineCollections). |
returns a matplotlib.patches.LineCollection object.
Draw state boundaries in Americas.
| Keyword | Description |
|---|---|
| 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 matplotlib.patches.LineCollections). |
returns a matplotlib.patches.LineCollection object.
Fill continents.
| Keyword | Description |
|---|---|
| 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.
returns a list of matplotlib.patches.Polygon objects.
compute points points along a great circle with endpoints (lon1,lat1) and (lon2,lat2).
Returns arrays x,y with map projection coordinates.
Display an image over the map (see matplotlib.pyplot.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.
Other **kwargs passed on to matplotlib.pyplot.plot.
returns an matplotlib.image.AxesImage instance.
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.
Shade the regions of the map that are in darkness at the time specifed by date. date is a datetime instance, assumed to be UTC.
| Keywords | Description |
|---|---|
| color | color to shade night regions (default black). |
| delta | day/night terminator is computed with a a resolution of delta degrees (default 0.25). |
| alpha | alpha transparency for shading (default 0.5, so map background shows through). |
| zorder | zorder for shading (default 2). |
Extra keyword ax can be used to override the default axis instance.
returns a matplotlib.contour.ContourSet instance.
Make a pseudo-color plot over the map (see matplotlib.pyplot.pcolor documentation).
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.
Other **kwargs passed on to matplotlib.pyplot.pcolor.
Make a pseudo-color plot over the map (see matplotlib.pyplot.pcolormesh documentation).
Extra keyword ax can be used to override the default axis instance.
Other **kwargs passed on to matplotlib.pyplot.pcolormesh.
Draw lines and/or markers on the map (see matplotlib.pyplot.plot documentation).
Extra keyword ax can be used to override the default axis instance.
Other **kwargs passed on to matplotlib.pyplot.plot.
Make a vector plot (u, v) with arrows on the map. (see matplotlib.pyplot.quiver documentation).
Extra keyword ax can be used to override the default axis instance.
Other *args and **kwargs passed on to matplotlib.pyplot.quiver.
Read in shape file, optionally draw boundaries on map.
Note
Mandatory Arguments:
| Argument | Description |
|---|---|
| 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 or points in 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 x,y vertices for each shape in map projection coordinates and self.counties_info will be a list of dictionaries with shape attributes. Rings in individual Polygon shapes are split out into separate polygons, and additional keys ‘RINGNUM’ and ‘SHAPENUM’ are added to the shape attribute dictionary. |
The following optional keyword arguments are only relevant for Polyline and Polygon shape types, for Point and MultiPoint shapes they are ignored.
| Keyword | Description |
|---|---|
| drawbounds | draw boundaries of shapes (default True). |
| zorder | shape boundary zorder (if not specified, default for mathplotlib.lines.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) |
A tuple (num_shapes, type, min, max) containing shape file info is returned. 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. If drawbounds=True a matplotlib.patches.LineCollection object is appended to the tuple.
Rotate a vector field (uin,vin) on a rectilinear grid with longitudes = lons and latitudes = lats from geographical (lat/lon) into map projection (x/y) coordinates.
Differs from transform_vector in that no interpolation is done. The vector is returned on the same grid, but rotated into x,y coordinates.
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.
| Arguments | Description |
|---|---|
| uin, vin | input vector field on a lat/lon grid. |
| lons, lats | Arrays containing longitudes and latitudes (in degrees) of input data in increasing order. For non-cylindrical projections (those other than cyl, merc, gall and mill) lons must fit within range -180 to 180. |
Returns uout, vout (rotated vector field). If the optional keyword argument returnxy is True (default is False), returns uout,vout,x,y (where x,y are the map projection coordinates of the grid defined by lons,lats).
Plot points with markers on the map (see matplotlib.pyplot.scatter documentation).
Extra keyword ax can be used to override the default axes instance.
Other **kwargs passed on to matplotlib.pyplot.scatter.
Draw a polygon centered at lon_0,lat_0. The polygon approximates a circle on the surface of the earth with radius radius_deg degrees latitude along longitude lon_0, made up of npts vertices. The polygon represents a Tissot’s indicatrix (http://en.wikipedia.org/wiki/Tissot’s_Indicatrix), which when drawn on a map shows the distortion inherent in the map projection.
Extra keyword ax can be used to override the default axis instance.
Other **kwargs passed on to matplotlib.patches.Polygon.
returns a matplotlib.patches.Polygon object.
Interpolate a scalar field (datin) from a lat/lon grid with longitudes = lons and latitudes = lats to a ny by nx map projection grid. Typically used to transform data to map projection coordinates for plotting on a map with the imshow().
| Argument | Description |
|---|---|
| datin | input data on a lat/lon grid. |
| lons, lats | rank-1 arrays containing longitudes and latitudes (in degrees) of input data in increasing order. For non-cylindrical projections (those other than cyl, merc, gall and mill) lons must fit within range -180 to 180. |
| nx, ny | The size of the output regular grid in map projection coordinates |
| Keyword | Description |
|---|---|
| returnxy | If True, the x and y values of the map projection grid are also returned (Default False). |
| checkbounds | If True, values of lons and lats are checked to see that they lie within the map projection region. Default is False, and data outside map projection region is clipped to values on boundary. |
| masked | If True, interpolated data is returned as a masked array with values outside map projection region masked (Default False). |
| order | 0 for nearest-neighbor interpolation, 1 for bilinear (Default 1). |
Returns datout (data on map projection grid). If returnxy=True, returns data,x,y.
Rotate and interpolate a vector field (uin,vin) from a lat/lon grid with longitudes = lons and latitudes = lats to a ny by nx map projection grid.
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.
| Arguments | Description |
|---|---|
| uin, vin | input vector field on a lat/lon grid. |
| lons, lats | rank-1 arrays containing longitudes and latitudes (in degrees) of input data in increasing order. For non-cylindrical projections (those other than cyl, merc, gall and mill) lons must fit within range -180 to 180. |
| nx, ny | The size of the output regular grid in map projection coordinates |
| Keyword | Description |
|---|---|
| returnxy | If True, the x and y values of the map projection grid are also returned (Default False). |
| checkbounds | If True, values of lons and lats are checked to see that they lie within the map projection region. Default is False, and data outside map projection region is clipped to values on boundary. |
| masked | If True, interpolated data is returned as a masked array with values outside map projection region masked (Default False). |
| order | 0 for nearest-neighbor interpolation, 1 for bilinear (Default 1). |
Returns uout, vout (vector field on map projection grid). If returnxy=True, returns uout,vout,x,y.
Display an image (filename given by image keyword) as a map background. If image is a URL (starts with ‘http’), it is downloaded to a temp file using urllib.urlretrieve.
Default (if image not specified) is to display ‘blue marble next generation’ image from http://visibleearth.nasa.gov/.
Specified image must have pixels covering the whole globe in a regular lat/lon grid, starting and -180W and the South Pole. Works with the global images from http://earthobservatory.nasa.gov/Features/BlueMarble/BlueMarble_monthlies.php.
The scale keyword can be used to downsample (rescale) the image. Values less than 1.0 will speed things up at the expense of image resolution.
Extra keyword ax can be used to override the default axis instance.
**kwargs passed on to imshow().
returns a matplotlib.image.AxesImage instance.
NetCDF File reader/writer. API is the same as Scientific.IO.NetCDF.
If file is a URL that starts with http, it is assumed to be a remote OPenDAP dataset, and pydap is used to retrieve the data. Only the OPenDAP Array and Grid data types are recognized. If file does not start with http, it is assumed to be a local netCDF file and is read with scipy.io.netcdf. Both pydap and scipy.io.netcdf are written by Roberto De Almeida.
Data will automatically be converted to and from masked arrays if the variable has either a missing_value or _FillValue attribute, and some data points are equal to the value specified by that attribute. In addition, variables that have the scale_factor and add_offset attribute will automatically be converted to and from short integers. To suppress these automatic conversions, set the maskandscale keyword to False.
The keywords cache, username, password and verbose are only valid for remote OPenDAP datasets. username and password are used to access OPenDAP datasets that require authentication. verbose=True will make the pydap client print out the URLs being accessed. cache is a location (a directory) for caching data, so that repeated accesses to the same URL avoid the network.
The keyword mmap is only valid for local netCDF files. When mmap=True (default), the mmap module is used to access the data. This may be slow for very large netCDF variables.
Return indices of a netCDF time variable corresponding to the given dates.
| Arguments | Description |
|---|---|
| dates | A datetime object or a sequence of datetime objects. The datetime objects should not include a time-zone offset. |
| nctime | A netCDF time variable object. The nctime object must have a units attribute. |
| Keywords | Description |
|---|---|
| calendar | describes the calendar used in the time calculations. All the values currently defined in the CF metadata convention (http://cf-pcmdi.llnl.gov/documents/cf-conventions/) are supported. Valid calendars standard, gregorian, proleptic_gregorian, noleap, 365_day, julian, all_leap, 366_day. Default is proleptic_gregorian. If calendar=None, will use calendar attribute of nctime object, and if that attribute does not exist calendar is set to standard. |
| select | The index selection method. exact wil return the indices perfectly matching the dates given. before and after will return the indices corresponding to the dates just before or after the given dates if an exact match cannot be found. nearest will return the indices that correspond to the closest dates. |
Returns an index or a sequence of indices.
Return numeric time values given datetime objects. The units of the numeric time values are described by the units argument and the calendar keyword. The datetime objects must be in UTC with no time-zone offset. If there is a time-zone offset in units, it will be applied to the returned numeric values.
Default behavior is the same as the matplotlib.dates.date2num function but the reference time and calendar can be changed via the units and calendar keywords.
| Arguments | Description |
|---|---|
| dates | A datetime object or a sequence of datetime objects. The datetime objects should not include a time-zone offset. |
| Keywords | Description |
|---|---|
| units | a string of the form ‘<time units> since <reference time>’ describing the units and origin of the time coordinate. <time units> can be days, hours, minutes or seconds. <reference time> is the time origin. Default is ‘days since 0001-01-01 00:00:00’. |
| calendar | describes the calendar used in the time calculations. All the values currently defined in the CF metadata convention (http://cf-pcmdi.llnl.gov/documents/cf-conventions/) are supported. Valid calendars standard, gregorian, proleptic_gregorian, noleap, 365_day, julian, all_leap, 366_day. Default is proleptic_gregorian. |
Returns a numeric time value, or an array of numeric time values.
The maximum resolution of the numeric time values is 1 second.
Interpolate data (datain) on a rectilinear grid (with x = xin y = yin) to a grid with x = xout, y= yout.
| Arguments | Description |
|---|---|
| datain | a rank-2 array with 1st dimension corresponding to y, 2nd dimension x. |
| xin, yin | rank-1 arrays containing x and y of datain grid in increasing order. |
| xout, yout | arrays containing x and y of desired output grid. |
| Keywords | Description |
|---|---|
| checkbounds | If True, values of xout and yout are checked to see that they lie within the range specified by xin and xin. If False, and xout,yout are outside xin,yin, interpolated values will be clipped to values on boundary of input grid (xin,yin) Default is False. |
| masked | If True, points outside the range of xin and yin are masked (in a masked array). If masked is set to a number, then points outside the range of xin and yin will be set to that number. Default False. |
| order | 0 for nearest-neighbor interpolation, 1 for bilinear interpolation (default 1). |
Note
If datain is a masked array and order=1 (bilinear interpolation) is used, elements of dataout will be masked if any of the four surrounding points in datain are masked. To avoid this, do the interpolation in two passes, first with order=1 (producing dataout1), then with order=0 (producing dataout2). Then replace all the masked values in dataout1 with the corresponding elements in dataout2 (using numpy.where). This effectively uses nearest neighbor interpolation if any of the four surrounding points in datain are masked, and bilinear interpolation otherwise.
Returns dataout, the interpolated data on the grid xout, yout.
mask data (datain), defined on a grid with latitudes latsin longitudes lonsin so that points over water will not be plotted.
| Arguments | Description |
|---|---|
| lonsin, latsin | rank-2 arrays containing longitudes and latitudes of grid. |
| datain | rank-2 input array on grid defined by lonsin and latsin. |
| inlands | if False, mask only ocean points. If True, mask ocean points and points over inland water bodies. Default False. |
returns a masked array the same shape as datain with “wet” points masked.
Return datetime objects given numeric time values. The units of the numeric time values are described by the units argument and the calendar keyword. The returned datetime objects represent UTC with no time-zone offset, even if the specified units contain a time-zone offset.
Default behavior is the same as the matplotlib.dates.num2date function but the reference time and calendar can be changed via the units and calendar keywords.
| Arguments | Description |
|---|---|
| times | numeric time values. Maximum resolution is 1 second. |
| Keywords | Description |
|---|---|
| units | a string of the form ‘<time units> since <reference time>’ describing the units and origin of the time coordinate. <time units> can be days, hours, minutes or seconds. <reference time> is the time origin. Default is ‘days since 0001-01-01 00:00:00’. |
| calendar | describes the calendar used in the time calculations. All the values currently defined in the CF metadata convention (http://cf-pcmdi.llnl.gov/documents/cf-conventions/) are supported. Valid calendars standard, gregorian, proleptic_gregorian, noleap, 365_day, julian, all_leap, 366_day. Default is proleptic_gregorian. |
Returns a datetime instance, or an array of datetime instances.
The datetime instances returned are ‘real’ python datetime objects if the date falls in the Gregorian calendar (i.e. calendar=``proleptic_gregorian``, or calendar = standard or gregorian and the date is after 1582-10-15). Otherwise, they are ‘phony’ datetime objects which support some but not all the methods of ‘real’ python datetime objects. The datetime instances do not contain a time-zone offset, even if the specified units contains one.
Shift global lat/lon grid east or west. assumes wraparound (or cyclic point) is included.
| Arguments | Description |
|---|---|
| lon0 | starting longitude for shifted grid (ending longitude if start=False). lon0 must be on input grid (within the range of lonsin). |
| datain | original data. |
| lonsin | original longitudes. |
| Keywords | Description |
|---|---|
| start | if True, lon0 represents the starting longitude of the new grid. if False, lon0 is the ending longitude. Default True. |
returns dataout,lonsout (data and longitudes on shifted grid).