Anaconda 5.0.0 JupyterLab 0.27.0 中使用 matplotlib basemap 绘制世界地图

来源:互联网 发布:淘宝卖家怎么做微淘 编辑:程序博客网 时间:2024/06/01 10:06

Anaconda 5.0.0 JupyterLab 0.27.0 中使用 matplotlib basemap 绘制世界地图

准备环境

安全的安装Anaconda3 5.0.0 Windows x86_64

http://blog.csdn.net/hu_zhenghui/article/details/78154684

Anaconda 5.0.0 JupyterLab 0.27.0 中配置多Python环境支持

http://blog.csdn.net/hu_zhenghui/article/details/78163081

正式开始

Python 中最常用的绘图库是 matplotlibAnaconda 5.0.0 中可以很方便的安装 matplotlibmatplotlib 的默认安装并不支持绘制地图,需要额外安装 basemap ,在 Anaconda 5.0.0 中搜索 basemap 可以找到,但是安装的时候会出现如图所示警告。

Anaconda 5.0.0 的默认环境不支持 basemap

从警告中可以看到,Anaconda 5.0.0 的默认环境的 Python 的版本是 3.6,而 basemap 依赖于 numpy 1.10 依赖于 python 2.7,为此,需要在 Anaconda 5.0.0 中创建一个 Python 2.7 版本的环境,单击 Create 按钮,出现 Create new environment 对话框,在 Name 文本框中输入 Python27,在 Packages 中选择 Python,在右侧的下拉列表框中选择 2.7,如图所示。

创建后的环境,并不能直接在 JupyterLab 0.27.0 中使用,需要参考前面的文章安装 ipykernel

安装成功后,运行 JupyterLab 0.27.0 ,在 Launcher 中可以看到 Python27,运行如下代码,可以看到版本号。

import sys
sys.version
'2.7.13 |Continuum Analytics, Inc.| (default, May 11 2017, 13:17:26) [MSC v.1500 64 bit (AMD64)]'

Anaconda 5.0.0 中,为 Python 2.7 环境添加 basemap

导入 matplotlib.pyplot

import matplotlib.pyplot

导入 mpl_toolkits.basemap

import mpl_toolkits.basemap

创建一个地图, mpl_toolkits.basemap.Basemap 的参数较多,详见本文末尾。

basemap = mpl_toolkits.basemap.Basemap()

在地图上绘制海岸线

basemap.drawcoastlines()
<matplotlib.collections.LineCollection at 0x9efee48>

绘制海岸线函数可以设定线宽、线型、颜色、抗锯齿等参数。

basemap.drawcoastlines?

    Signature: basemap.drawcoastlines(linewidth=1.0, linestyle='solid', color='k', antialiased=1, ax=None, zorder=None)
    Docstring:
    Draw coastlines.
    
    .. tabularcolumns:: |l|L|
    
    ==============   ====================================================
    Keyword          Description
    ==============   ====================================================
    linewidth        coastline width (default 1.)
    linestyle        coastline linestyle (default solid)
    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.
    File:      c:\users\huzh\appdata\local\conda\conda\envs\python27\lib\site-packages\mpl_toolkits\basemap\__init__.py
    Type:      instancemethod
    

保存图片

matplotlib.pyplot.savefig('world.png')

就得到了一张世界地图

mpl_toolkits.basemap.Basemap?

    Init signature: mpl_toolkits.basemap.Basemap(self, llcrnrlon=None, llcrnrlat=None, urcrnrlon=None, urcrnrlat=None, llcrnrx=None, llcrnry=None, urcrnrx=None, urcrnry=None, width=None, height=None, projection='cyl', resolution='c', area_thresh=None, rsphere=6370997.0, ellps=None, lat_ts=None, lat_1=None, lat_2=None, lat_0=None, lon_0=None, lon_1=None, lon_2=None, o_lon_p=None, o_lat_p=None, k_0=None, no_rot=False, suppress_ticks=True, satellite_height=35786000, boundinglat=None, fix_aspect=True, anchor='C', celestial=False, round=False, epsg=None, ax=None)
    Docstring:      <no docstring>
    Init docstring:
    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
    ==============   ====================================================
    cea              Cylindrical Equal Area                  
    mbtfpq           McBryde-Thomas Flat-Polar Quartic       
    aeqd             Azimuthal Equidistant                   
    sinu             Sinusoidal                              
    poly             Polyconic                               
    omerc            Oblique Mercator                        
    gnom             Gnomonic                                
    moll             Mollweide                               
    lcc              Lambert Conformal                       
    tmerc            Transverse Mercator                     
    nplaea           North-Polar Lambert Azimuthal           
    gall             Gall Stereographic Cylindrical          
    npaeqd           North-Polar Azimuthal Equidistant       
    mill             Miller Cylindrical                      
    merc             Mercator                                
    stere            Stereographic                           
    eqdc             Equidistant Conic                       
    rotpole          Rotated Pole                            
    cyl              Cylindrical Equidistant                 
    npstere          North-Polar Stereographic               
    spstere          South-Polar Stereographic               
    hammer           Hammer                                  
    geos             Geostationary                           
    nsper            Near-Sided Perspective                  
    eck4             Eckert IV                               
    aea              Albers Equal Area                       
    kav7             Kavrayskiy VII                          
    spaeqd           South-Polar Azimuthal Equidistant       
    ortho            Orthographic                            
    cass             Cassini-Soldner                         
    vandg            van der Grinten                         
    laea             Lambert Azimuthal Equal Area            
    splaea           South-Polar Lambert Azimuthal           
    robin            Robinson                                
    
    ==============   ====================================================
    
    For most map projections, the map projection region can either be
    specified by setting these keywords:
    
    .. tabularcolumns:: |l|L|
    
    ==============   ====================================================
    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
    
    .. tabularcolumns:: |l|L|
    
    ==============   ====================================================
    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, hammer, npstere, spstere, nplaea, splaea,
    npaeqd, spaeqd, robin, eck4, kav7, 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, cea  and gall),
    the default is to use
    llcrnrlon=-180,llcrnrlat=-90, urcrnrlon=180 and urcrnrlat=90). For all other
    projections except ortho, geos and nsper, either the lat/lon values of the
    corners or width and height must be specified by the user.
    
    For ortho, geos and nsper, 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.
    
    For rotpole, the lat/lon values of the corners on the unrotated sphere
    may be provided as llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat, or the lat/lon
    values of the corners on the rotated sphere can be given as
    llcrnrx,llcrnry,urcrnrx,urcrnry.
    
    Other keyword arguments:
    
    .. tabularcolumns:: |l|L|
    
    ==============   ====================================================
    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).
    ellps            string describing ellipsoid ('GRS80' or 'WGS84',
                     for example). If both rsphere and ellps are given,
                     rsphere is ignored. Default None. See pyproj.pj_ellps
                     for allowed values.
    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.
    celestial        use astronomical conventions for longitude (i.e.
                     negative longitudes to the east of 0). Default False.
                     Implies resolution=None.
    ax               set default axes instance
                     (default None - matplotlib.pyplot.gca() may be used
                     to get the current axes instance).
                     If you don not 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&#95;params is a dictionary which
    lists which parameters apply to which projections.
    
    .. tabularcolumns:: |l|L|
    
    ================ ====================================================
    Keyword          Description
    ================ ====================================================
    lat_ts           latitude of true scale. Optional for stereographic,
                     cylindrical equal area and mercator projections.
                     default is lat_0 for stereographic projection.
                     default is 0 for mercator and cylindrical equal area
                     projections.
    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.
    k_0              Scale factor at natural origin (used
                     by 'tmerc', 'omerc', 'stere' and 'lcc').
    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.
    round            cut off pole-centered projection at boundinglat
                     (so plot is a circle instead of a square). Only
                     relevant for npstere,spstere,nplaea,splaea,npaeqd
                     or spaeqd projections. Default False.
    satellite_height height of satellite (in m) above equator -
                     only relevant for geostationary
                     and near-sided perspective (geos or nsper)
                     projections. Default 35,786 km.
    ================ ====================================================
    
    Useful instance variables:
    
    .. tabularcolumns:: |l|L|
    
    ================ ====================================================
    Variable Name    Description
    ================ ====================================================
    projection       map projection. Print the module variable
                     supported&#95;projections to see a list of allowed
                     values.
    epsg             EPSG code defining projection (see
                     http://spatialreference.org for a list of
                     EPSG codes and their definitions).
    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,
    cea, gall or merc)
    the inverse transformation will return 

阅读全文
0 0