示例#1
0
文件: fitsfunc.py 项目: jrs65/healpy
def write_map(filename,m,nest=False,dtype=np.float32,fits_IDL=True,coord=None,column_names=None):
    """Writes an healpix map into an healpix file.

    Parameters
    ----------
    filename : str
      the fits file name
    m : array or sequence of 3 arrays
      the map to write. Possibly a sequence of 3 maps of same size.
      They will be considered as I, Q, U maps. 
      Supports masked maps, see the `ma` function.
    nest : bool, optional
      If True, ordering scheme is assumed to be NESTED, otherwise, RING. Default: RING.
      The map ordering is not modified by this function, the input map array
      should already be in the desired ordering (run `ud_grade` beforehand).
    fits_IDL : bool, optional
      If True, reshapes columns in rows of 1024, otherwise all the data will 
      go in one column. Default: True
    coord : str
      The coordinate system, typically 'E' for Ecliptic, 'G' for Galactic or 'C' for
      Celestial (equatorial)
    column_names : str or list
      Column name or list of column names, if None we use:
      I_STOKES for 1 component,
      I/Q/U_STOKES for 3 components,
      II, IQ, IU, QQ, QU, UU for 6 components,
      COLUMN_0, COLUMN_1... otherwise
    """
    if not hasattr(m, '__len__'):
        raise TypeError('The map must be a sequence')
    # check the dtype and convert it
    fitsformat = getformat(dtype)

    m = pixelfunc.ma_to_array(m)
    if pixelfunc.maptype(m) == 0: # a single map is converted to a list
        m = [m]

    if column_names is None:
        column_names = standard_column_names.get(len(m), ["COLUMN_%d" % n for n in range(len(m))])
    else:
        assert len(column_names) == len(m), "Length column_names != number of maps"

    # maps must have same length
    assert len(set(map(len, m))) == 1, "Maps must have same length"
    nside = pixelfunc.npix2nside(len(m[0]))

    if nside < 0:
        raise ValueError('Invalid healpix map : wrong number of pixel')

    cols=[]
    for cn, mm in zip(column_names, m):
        if len(mm) > 1024 and fits_IDL:
            # I need an ndarray, for reshape:
            mm2 = np.asarray(mm)
            cols.append(pf.Column(name=cn,
                                   format='1024%s' % fitsformat,
                                   array=mm2.reshape(mm2.size/1024,1024)))
        else:
            cols.append(pf.Column(name=cn,
                                   format='%s' % fitsformat,
                                   array=mm))
            
    tbhdu = pf.new_table(cols)
    # add needed keywords
    tbhdu.header.update('PIXTYPE','HEALPIX','HEALPIX pixelisation')
    if nest: ordering = 'NESTED'
    else:    ordering = 'RING'
    tbhdu.header.update('ORDERING',ordering,
                        'Pixel ordering scheme, either RING or NESTED')
    if coord:
        tbhdu.header.update('COORDSYS',coord,
                            'Ecliptic, Galactic or Celestial (equatorial)')
    tbhdu.header.update('EXTNAME','xtension',
                        'name of this binary table extension')
    tbhdu.header.update('NSIDE',nside,'Resolution parameter of HEALPIX')
    tbhdu.header.update('FIRSTPIX', 0, 'First pixel # (0 based)')
    tbhdu.header.update('LASTPIX',pixelfunc.nside2npix(nside)-1,
                        'Last pixel # (0 based)')
    tbhdu.header.update('INDXSCHM','IMPLICIT',
                        'Indexing: IMPLICIT or EXPLICIT')
    tbhdu.writeto(filename,clobber=True)
示例#2
0
def write_map(filename,
              m,
              nest=False,
              dtype=np.float32,
              fits_IDL=True,
              coord=None):
    """Writes an healpix map into an healpix file.

    Parameters
    ----------
    filename : str
      the fits file name
    m : array or sequence of 3 arrays
      the map to write. Possibly a sequence of 3 maps of same size.
      They will be considered as I, Q, U maps. 
      Supports masked maps, see the `ma` function.
    nest : bool, optional
      If False, ordering scheme is NESTED, otherwise, it is RING. Default: RING.
    fits_IDL : bool, optional
      If True, reshapes columns in rows of 1024, otherwise all the data will 
      go in one column. Default: True
    coord : str
      The coordinate system, typically 'E' for Ecliptic, 'G' for Galactic or 'Q' for Equatorial  
    """
    if not hasattr(m, '__len__'):
        raise TypeError('The map must be a sequence')
    # check the dtype and convert it
    fitsformat = getformat(dtype)
    #print 'format to use: "%s"'%fitsformat
    if hasattr(m[0], '__len__'):
        # we should have three maps
        if len(m) != 3 or len(m[1]) != len(m[0]) or len(m[2]) != len(m[0]):
            raise ValueError("You should give 3 maps of same size "
                             "for polarisation...")
        nside = pixelfunc.npix2nside(len(m[0]))
        if nside < 0:
            raise ValueError('Invalid healpix map : wrong number of pixel')
        m = pixelfunc.ma_to_array(m)
        cols = []
        colnames = ['I_STOKES', 'Q_STOKES', 'U_STOKES']
        for cn, mm in zip(colnames, m):
            if len(mm) > 1024 and fits_IDL:
                # I need an ndarray, for reshape:
                mm2 = np.asarray(mm)
                cols.append(
                    pf.Column(name=cn,
                              format='1024%s' % fitsformat,
                              array=mm2.reshape(mm2.size / 1024, 1024)))
            else:
                cols.append(
                    pf.Column(name=cn, format='%s' % fitsformat, array=mm))
    else:  # we write only one map
        nside = pixelfunc.npix2nside(len(m))
        if nside < 0:
            raise ValueError('Invalid healpix map : wrong number of pixel')
        if m.size > 1024 and fits_IDL:
            cols = [
                pf.Column(name='I_STOKES',
                          format='1024%s' % fitsformat,
                          array=m.reshape(m.size / 1024, 1024))
            ]
        else:
            cols = [
                pf.Column(name='I_STOKES', format='%s' % fitsformat, array=m)
            ]

    tbhdu = pf.new_table(cols)
    # add needed keywords
    tbhdu.header.update('PIXTYPE', 'HEALPIX', 'HEALPIX pixelisation')
    if nest: ordering = 'NESTED'
    else: ordering = 'RING'
    tbhdu.header.update('ORDERING', ordering,
                        'Pixel ordering scheme, either RING or NESTED')
    if coord:
        tbhdu.header.update('COORDSYS', coord,
                            'Ecliptic, Galactic or eQuatorial')
    tbhdu.header.update('EXTNAME', 'xtension',
                        'name of this binary table extension')
    tbhdu.header.update('NSIDE', nside, 'Resolution parameter of HEALPIX')
    tbhdu.header.update('FIRSTPIX', 0, 'First pixel # (0 based)')
    tbhdu.header.update('LASTPIX',
                        pixelfunc.nside2npix(nside) - 1,
                        'Last pixel # (0 based)')
    tbhdu.header.update('INDXSCHM', 'IMPLICIT',
                        'Indexing: IMPLICIT or EXPLICIT')
    tbhdu.writeto(filename, clobber=True)
示例#3
0
def mollview(
    map=None,
    fig=None,
    rot=None,
    coord=None,
    unit="",
    xsize=800,
    title="Mollweide view",
    nest=False,
    min=None,
    max=None,
    flip="astro",
    remove_dip=False,
    remove_mono=False,
    gal_cut=0,
    format="%g",
    format2="%g",
    cbar=True,
    cmap=None,
    notext=False,
    norm=None,
    hold=False,
    margins=None,
    sub=None,
):
    """Plot an healpix map (given as an array) in Mollweide projection.
    
    Parameters
    ----------
    map : float, array-like or None
      An array containing the map, supports masked maps, see the `ma` function.
      If None, will display a blank map, useful for overplotting.
    fig : int or None, optional
      The figure number to use. Default: create a new figure
    rot : scalar or sequence, optional
      Describe the rotation to apply.
      In the form (lon, lat, psi) (unit: degrees) : the point at
      longitude *lon* and latitude *lat* will be at the center. An additional rotation
      of angle *psi* around this direction is applied.
    coord : sequence of character, optional
      Either one of 'G', 'E' or 'C' to describe the coordinate
      system of the map, or a sequence of 2 of these to rotate
      the map from the first to the second coordinate system.
    unit : str, optional
      A text describing the unit of the data. Default: ''
    xsize : int, optional
      The size of the image. Default: 800
    title : str, optional
      The title of the plot. Default: 'Mollweide view'
    nest : bool, optional
      If True, ordering scheme is NESTED. Default: False (RING)
    min : float, optional
      The minimum range value
    max : float, optional
      The maximum range value
    flip : {'astro', 'geo'}, optional
      Defines the convention of projection : 'astro' (default, east towards left, west towards right)
      or 'geo' (east towards roght, west towards left)
    remove_dip : bool, optional
      If :const:`True`, remove the dipole+monopole
    remove_mono : bool, optional
      If :const:`True`, remove the monopole
    gal_cut : float, scalar, optional
      Symmetric galactic cut for the dipole/monopole fit.
      Removes points in latitude range [-gal_cut, +gal_cut]
    format : str, optional
      The format of the scale label. Default: '%g'
    format2 : str, optional
      Format of the pixel value under mouse. Default: '%g'
    cbar : bool, optional
      Display the colorbar. Default: True
    notext : bool, optional
      If True, no text is printed around the map
    norm : {'hist', 'log', None}
      Color normalization, hist= histogram equalized color mapping,
      log= logarithmic color mapping, default: None (linear color mapping)
    hold : bool, optional
      If True, replace the current Axes by a MollweideAxes.
      use this if you want to have multiple maps on the same
      figure. Default: False
    sub : int, scalar or sequence, optional
      Use only a zone of the current figure (same syntax as subplot).
      Default: None
    margins : None or sequence, optional
      Either None, or a sequence (left,bottom,right,top)
      giving the margins on left,bottom,right and top
      of the axes. Values are relative to figure (0-1).
      Default: None

    See Also
    --------
    gnomview, cartview
    """
    # Create the figure
    import pylab

    if not (hold or sub):
        f = pylab.figure(fig, figsize=(8.5, 5.4))
        extent = (0.02, 0.05, 0.96, 0.9)
    elif hold:
        f = pylab.gcf()
        left, bottom, right, top = np.array(f.gca().get_position()).ravel()
        extent = (left, bottom, right - left, top - bottom)
        f.delaxes(f.gca())
    else:  # using subplot syntax
        f = pylab.gcf()
        if hasattr(sub, "__len__"):
            nrows, ncols, idx = sub
        else:
            nrows, ncols, idx = sub / 100, (sub % 100) / 10, (sub % 10)
        if idx < 1 or idx > ncols * nrows:
            raise ValueError("Wrong values for sub: %d, %d, %d" % (nrows, ncols, idx))
        c, r = (idx - 1) % ncols, (idx - 1) / ncols
        if not margins:
            margins = (0.01, 0.0, 0.0, 0.02)
        extent = (
            c * 1.0 / ncols + margins[0],
            1.0 - (r + 1) * 1.0 / nrows + margins[1],
            1.0 / ncols - margins[2] - margins[0],
            1.0 / nrows - margins[3] - margins[1],
        )
        extent = (
            extent[0] + margins[0],
            extent[1] + margins[1],
            extent[2] - margins[2] - margins[0],
            extent[3] - margins[3] - margins[1],
        )
        # extent = (c*1./ncols, 1.-(r+1)*1./nrows,1./ncols,1./nrows)
    # f=pylab.figure(fig,figsize=(8.5,5.4))

    # Starting to draw : turn interactive off
    wasinteractive = pylab.isinteractive()
    pylab.ioff()
    try:
        if map is None:
            map = np.zeros(12) + np.inf
            cbar = False
        map = pixelfunc.ma_to_array(map)
        ax = PA.HpxMollweideAxes(f, extent, coord=coord, rot=rot, format=format2, flipconv=flip)
        f.add_axes(ax)
        if remove_dip:
            map = pixelfunc.remove_dipole(map, gal_cut=gal_cut, nest=nest, copy=True, verbose=True)
        elif remove_mono:
            map = pixelfunc.remove_monopole(map, gal_cut=gal_cut, nest=nest, copy=True, verbose=True)
        ax.projmap(map, nest=nest, xsize=xsize, coord=coord, vmin=min, vmax=max, cmap=cmap, norm=norm)
        if cbar:
            im = ax.get_images()[0]
            b = im.norm.inverse(np.linspace(0, 1, im.cmap.N + 1))
            v = np.linspace(im.norm.vmin, im.norm.vmax, im.cmap.N)
            if matplotlib.__version__ >= "0.91.0":
                cb = f.colorbar(
                    im,
                    ax=ax,
                    orientation="horizontal",
                    shrink=0.5,
                    aspect=25,
                    ticks=PA.BoundaryLocator(),
                    pad=0.05,
                    fraction=0.1,
                    boundaries=b,
                    values=v,
                    format=format,
                )
            else:
                # for older matplotlib versions, no ax kwarg
                cb = f.colorbar(
                    im,
                    orientation="horizontal",
                    shrink=0.5,
                    aspect=25,
                    ticks=PA.BoundaryLocator(),
                    pad=0.05,
                    fraction=0.1,
                    boundaries=b,
                    values=v,
                    format=format,
                )
        ax.set_title(title)
        if not notext:
            ax.text(0.86, 0.05, ax.proj.coordsysstr, fontsize=14, fontweight="bold", transform=ax.transAxes)
        if cbar:
            cb.ax.text(0.5, -1.0, unit, fontsize=14, transform=cb.ax.transAxes, ha="center", va="center")
        f.sca(ax)
    finally:
        pylab.draw()
        if wasinteractive:
            pylab.ion()
示例#4
0
def write_map(filename,m,nest=False,dtype=np.float32,fits_IDL=True,coord=None):
    """Writes an healpix map into an healpix file.

    Parameters
    ----------
    filename : str
      the fits file name
    m : array or sequence of 3 arrays
      the map to write. Possibly a sequence of 3 maps of same size.
      They will be considered as I, Q, U maps. 
      Supports masked maps, see the `ma` function.
    nest : bool, optional
      If False, ordering scheme is NESTED, otherwise, it is RING. Default: RING.
    fits_IDL : bool, optional
      If True, reshapes columns in rows of 1024, otherwise all the data will 
      go in one column. Default: True
    coord : str
      The coordinate system, typically 'E' for Ecliptic, 'G' for Galactic or 'Q' for Equatorial  
    """
    if not hasattr(m, '__len__'):
        raise TypeError('The map must be a sequence')
    # check the dtype and convert it
    fitsformat = getformat(dtype)
    #print 'format to use: "%s"'%fitsformat
    if hasattr(m[0], '__len__'):
        # we should have three maps
        if len(m) != 3 or len(m[1]) != len(m[0]) or len(m[2]) != len(m[0]):
            raise ValueError("You should give 3 maps of same size "
                             "for polarisation...")
        nside = pixelfunc.npix2nside(len(m[0]))
        if nside < 0:
            raise ValueError('Invalid healpix map : wrong number of pixel')
        m = pixelfunc.ma_to_array(m)
        cols=[]
        colnames=['I_STOKES','Q_STOKES','U_STOKES']
        for cn,mm in zip(colnames,m):
            if len(mm) > 1024 and fits_IDL:
                # I need an ndarray, for reshape:
                mm2 = np.asarray(mm)
                cols.append(pf.Column(name=cn,
                                       format='1024%s'%fitsformat,
                                       array=mm2.reshape(mm2.size/1024,1024)))
            else:
                cols.append(pf.Column(name=cn,
                                       format='%s'%fitsformat,
                                       array=mm))
    else: # we write only one map
        nside = pixelfunc.npix2nside(len(m))
        if nside < 0:
            raise ValueError('Invalid healpix map : wrong number of pixel')
        if m.size > 1024 and fits_IDL:
            cols = [pf.Column(name='I_STOKES',
                               format='1024%s'%fitsformat,
                               array=m.reshape(m.size/1024,1024))]
        else:
            cols = [pf.Column(name='I_STOKES',
                               format='%s'%fitsformat,
                               array=m)]
            
    tbhdu = pf.new_table(cols)
    # add needed keywords
    tbhdu.header.update('PIXTYPE','HEALPIX','HEALPIX pixelisation')
    if nest: ordering = 'NESTED'
    else:    ordering = 'RING'
    tbhdu.header.update('ORDERING',ordering,
                        'Pixel ordering scheme, either RING or NESTED')
    if coord:
        tbhdu.header.update('COORDSYS',coord,
                            'Ecliptic, Galactic or eQuatorial')
    tbhdu.header.update('EXTNAME','xtension',
                        'name of this binary table extension')
    tbhdu.header.update('NSIDE',nside,'Resolution parameter of HEALPIX')
    tbhdu.header.update('FIRSTPIX', 0, 'First pixel # (0 based)')
    tbhdu.header.update('LASTPIX',pixelfunc.nside2npix(nside)-1,
                        'Last pixel # (0 based)')
    tbhdu.header.update('INDXSCHM','IMPLICIT',
                        'Indexing: IMPLICIT or EXPLICIT')
    tbhdu.writeto(filename,clobber=True)
示例#5
0
def gnomview(
    map=None,
    fig=None,
    rot=None,
    coord=None,
    unit="",
    xsize=200,
    ysize=None,
    reso=1.5,
    degree=False,
    title="Gnomonic view",
    nest=False,
    remove_dip=False,
    remove_mono=False,
    gal_cut=0,
    min=None,
    max=None,
    flip="astro",
    format="%.3g",
    cbar=True,
    cmap=None,
    norm=None,
    hold=False,
    sub=None,
    margins=None,
    notext=False,
):
    """Plot an healpix map (given as an array) in Gnomonic projection.

    Parameters
    ----------
    map : array-like
      The map to project, supports masked maps, see the `ma` function.
      If None, use a blank map, useful for
      overplotting.
    fig : None or int, optional
      A figure number. Default: None= create a new figure
    rot : scalar or sequence, optional
      Describe the rotation to apply.
      In the form (lon, lat, psi) (unit: degrees) : the point at
      longitude *lon* and latitude *lat* will be at the center. An additional rotation
      of angle *psi* around this direction is applied.
    coord : sequence of character, optional
      Either one of 'G', 'E' or 'C' to describe the coordinate
      system of the map, or a sequence of 2 of these to rotate
      the map from the first to the second coordinate system.
    unit : str, optional
      A text describing the unit of the data. Default: ''
    xsize : int, optional
      The size of the image. Default: 200
    ysize : None or int, optional
      The size of the image. Default: None= xsize
    reso : float, optional
      Resolution (in arcmin if degree is False). Default: 1.5 arcmin
    degree : bool, optional
      if True, reso is in degree. Default: False
    title : str, optional
      The title of the plot. Default: 'Gnomonic view'
    nest : bool, optional
      If True, ordering scheme is NESTED. Default: False (RING)
    min : float, scalar, optional
      The minimum range value
    max : float, scalar, optional
      The maximum range value
    flip : {'astro', 'geo'}, optional
      Defines the convention of projection : 'astro' (default, east towards left, west towards right)
      or 'geo' (east towards roght, west towards left)
    remove_dip : bool, optional
      If :const:`True`, remove the dipole+monopole
    remove_mono : bool, optional
      If :const:`True`, remove the monopole
    gal_cut : float, scalar, optional
      Symmetric galactic cut for the dipole/monopole fit.
      Removes points in latitude range [-gal_cut, +gal_cut]
    format : str, optional
      The format of the scale label. Default: '%g'
    hold : bool, optional
      If True, replace the current Axes by a MollweideAxes.
      use this if you want to have multiple maps on the same
      figure. Default: False
    sub : int or sequence, optional
      Use only a zone of the current figure (same syntax as subplot).
      Default: None
    margins : None or sequence, optional
      Either None, or a sequence (left,bottom,right,top)
      giving the margins on left,bottom,right and top
      of the axes. Values are relative to figure (0-1).
      Default: None
    notext: bool, optional
      If True: do not add resolution info text. Default=False

    See Also
    --------
    mollview, cartview
    """
    import pylab

    if not (hold or sub):
        f = pylab.figure(fig, figsize=(5.8, 6.4))
        if not margins:
            margins = (0.075, 0.05, 0.075, 0.05)
        extent = (0.0, 0.0, 1.0, 1.0)
    elif hold:
        f = pylab.gcf()
        left, bottom, right, top = np.array(pylab.gca().get_position()).ravel()
        if not margins:
            margins = (0.0, 0.0, 0.0, 0.0)
        extent = (left, bottom, right - left, top - bottom)
        f.delaxes(pylab.gca())
    else:  # using subplot syntax
        f = pylab.gcf()
        if hasattr(sub, "__len__"):
            nrows, ncols, idx = sub
        else:
            nrows, ncols, idx = sub / 100, (sub % 100) / 10, (sub % 10)
        if idx < 1 or idx > ncols * nrows:
            raise ValueError("Wrong values for sub: %d, %d, %d" % (nrows, ncols, idx))
        c, r = (idx - 1) % ncols, (idx - 1) / ncols
        if not margins:
            margins = (0.01, 0.0, 0.0, 0.02)
        extent = (
            c * 1.0 / ncols + margins[0],
            1.0 - (r + 1) * 1.0 / nrows + margins[1],
            1.0 / ncols - margins[2] - margins[0],
            1.0 / nrows - margins[3] - margins[1],
        )
    extent = (
        extent[0] + margins[0],
        extent[1] + margins[1],
        extent[2] - margins[2] - margins[0],
        extent[3] - margins[3] - margins[1],
    )
    # f=pylab.figure(fig,figsize=(5.5,6))

    # Starting to draw : turn interactive off
    wasinteractive = pylab.isinteractive()
    pylab.ioff()
    try:
        if map is None:
            map = np.zeros(12) + np.inf
            cbar = False
        map = pixelfunc.ma_to_array(map)
        ax = PA.HpxGnomonicAxes(f, extent, coord=coord, rot=rot, format=format, flipconv=flip)
        f.add_axes(ax)
        if remove_dip:
            map = pixelfunc.remove_dipole(map, gal_cut=gal_cut, nest=nest, copy=True)
        elif remove_mono:
            map = pixelfunc.remove_monopole(map, gal_cut=gal_cut, nest=nest, copy=True)
        ax.projmap(
            map, nest=nest, coord=coord, vmin=min, vmax=max, xsize=xsize, ysize=ysize, reso=reso, cmap=cmap, norm=norm
        )
        if cbar:
            im = ax.get_images()[0]
            b = im.norm.inverse(np.linspace(0, 1, im.cmap.N + 1))
            v = np.linspace(im.norm.vmin, im.norm.vmax, im.cmap.N)
            if matplotlib.__version__ >= "0.91.0":
                cb = f.colorbar(
                    im,
                    ax=ax,
                    orientation="horizontal",
                    shrink=0.5,
                    aspect=25,
                    ticks=PA.BoundaryLocator(),
                    pad=0.08,
                    fraction=0.1,
                    boundaries=b,
                    values=v,
                    format=format,
                )
            else:
                cb = f.colorbar(
                    im,
                    orientation="horizontal",
                    shrink=0.5,
                    aspect=25,
                    ticks=PA.BoundaryLocator(),
                    pad=0.08,
                    fraction=0.1,
                    boundaries=b,
                    values=v,
                    format=format,
                )
        ax.set_title(title)
        if not notext:
            ax.text(
                -0.07,
                0.02,
                "%g '/pix,   %dx%d pix"
                % (ax.proj.arrayinfo["reso"], ax.proj.arrayinfo["xsize"], ax.proj.arrayinfo["ysize"]),
                fontsize=12,
                verticalalignment="bottom",
                transform=ax.transAxes,
                rotation=90,
            )
            ax.text(
                -0.07, 0.6, ax.proj.coordsysstr, fontsize=14, fontweight="bold", rotation=90, transform=ax.transAxes
            )
            lon, lat = np.around(ax.proj.get_center(lonlat=True), ax._coordprec)
            ax.text(
                0.5,
                -0.03,
                "(%g,%g)" % (lon, lat),
                verticalalignment="center",
                horizontalalignment="center",
                transform=ax.transAxes,
            )
        if cbar:
            cb.ax.text(
                1.05, 0.30, unit, fontsize=14, fontweight="bold", transform=cb.ax.transAxes, ha="left", va="center"
            )
        f.sca(ax)
    finally:
        pylab.draw()
        if wasinteractive:
            pylab.ion()
示例#6
0
def mollview(map=None,
             fig=None,
             rot=None,
             coord=None,
             unit='',
             xsize=800,
             title='Mollweide view',
             nest=False,
             min=None,
             max=None,
             flip='astro',
             remove_dip=False,
             remove_mono=False,
             gal_cut=0,
             format='%g',
             format2='%g',
             cbar=True,
             cmap=None,
             notext=False,
             norm=None,
             hold=False,
             margins=None,
             sub=None):
    """Plot an healpix map (given as an array) in Mollweide projection.
    
    Parameters
    ----------
    map : float, array-like or None
      An array containing the map, supports masked maps, see the `ma` function.
      If None, will display a blank map, useful for overplotting.
    fig : int or None, optional
      The figure number to use. Default: create a new figure
    rot : scalar or sequence, optional
      Describe the rotation to apply.
      In the form (lon, lat, psi) (unit: degrees) : the point at
      longitude *lon* and latitude *lat* will be at the center. An additional rotation
      of angle *psi* around this direction is applied.
    coord : sequence of character, optional
      Either one of 'G', 'E' or 'C' to describe the coordinate
      system of the map, or a sequence of 2 of these to rotate
      the map from the first to the second coordinate system.
    unit : str, optional
      A text describing the unit of the data. Default: ''
    xsize : int, optional
      The size of the image. Default: 800
    title : str, optional
      The title of the plot. Default: 'Mollweide view'
    nest : bool, optional
      If True, ordering scheme is NESTED. Default: False (RING)
    min : float, optional
      The minimum range value
    max : float, optional
      The maximum range value
    flip : {'astro', 'geo'}, optional
      Defines the convention of projection : 'astro' (default, east towards left, west towards right)
      or 'geo' (east towards roght, west towards left)
    remove_dip : bool, optional
      If :const:`True`, remove the dipole+monopole
    remove_mono : bool, optional
      If :const:`True`, remove the monopole
    gal_cut : float, scalar, optional
      Symmetric galactic cut for the dipole/monopole fit.
      Removes points in latitude range [-gal_cut, +gal_cut]
    format : str, optional
      The format of the scale label. Default: '%g'
    format2 : str, optional
      Format of the pixel value under mouse. Default: '%g'
    cbar : bool, optional
      Display the colorbar. Default: True
    notext : bool, optional
      If True, no text is printed around the map
    norm : {'hist', 'log', None}
      Color normalization, hist= histogram equalized color mapping,
      log= logarithmic color mapping, default: None (linear color mapping)
    hold : bool, optional
      If True, replace the current Axes by a MollweideAxes.
      use this if you want to have multiple maps on the same
      figure. Default: False
    sub : int, scalar or sequence, optional
      Use only a zone of the current figure (same syntax as subplot).
      Default: None
    margins : None or sequence, optional
      Either None, or a sequence (left,bottom,right,top)
      giving the margins on left,bottom,right and top
      of the axes. Values are relative to figure (0-1).
      Default: None

    See Also
    --------
    gnomview, cartview
    """
    # Create the figure
    import pylab
    if not (hold or sub):
        f = pylab.figure(fig, figsize=(8.5, 5.4))
        extent = (0.02, 0.05, 0.96, 0.9)
    elif hold:
        f = pylab.gcf()
        left, bottom, right, top = np.array(f.gca().get_position()).ravel()
        extent = (left, bottom, right - left, top - bottom)
        f.delaxes(f.gca())
    else:  # using subplot syntax
        f = pylab.gcf()
        if hasattr(sub, '__len__'):
            nrows, ncols, idx = sub
        else:
            nrows, ncols, idx = sub / 100, (sub % 100) / 10, (sub % 10)
        if idx < 1 or idx > ncols * nrows:
            raise ValueError('Wrong values for sub: %d, %d, %d' %
                             (nrows, ncols, idx))
        c, r = (idx - 1) % ncols, (idx - 1) / ncols
        if not margins:
            margins = (0.01, 0.0, 0.0, 0.02)
        extent = (c * 1. / ncols + margins[0],
                  1. - (r + 1) * 1. / nrows + margins[1],
                  1. / ncols - margins[2] - margins[0],
                  1. / nrows - margins[3] - margins[1])
        extent = (extent[0] + margins[0], extent[1] + margins[1],
                  extent[2] - margins[2] - margins[0],
                  extent[3] - margins[3] - margins[1])
        #extent = (c*1./ncols, 1.-(r+1)*1./nrows,1./ncols,1./nrows)
    #f=pylab.figure(fig,figsize=(8.5,5.4))

    # Starting to draw : turn interactive off
    wasinteractive = pylab.isinteractive()
    pylab.ioff()
    try:
        if map is None:
            map = np.zeros(12) + np.inf
            cbar = False
        map = pixelfunc.ma_to_array(map)
        ax = PA.HpxMollweideAxes(f,
                                 extent,
                                 coord=coord,
                                 rot=rot,
                                 format=format2,
                                 flipconv=flip)
        f.add_axes(ax)
        if remove_dip:
            map = pixelfunc.remove_dipole(map,
                                          gal_cut=gal_cut,
                                          nest=nest,
                                          copy=True,
                                          verbose=True)
        elif remove_mono:
            map = pixelfunc.remove_monopole(map,
                                            gal_cut=gal_cut,
                                            nest=nest,
                                            copy=True,
                                            verbose=True)
        ax.projmap(map,
                   nest=nest,
                   xsize=xsize,
                   coord=coord,
                   vmin=min,
                   vmax=max,
                   cmap=cmap,
                   norm=norm)
        if cbar:
            im = ax.get_images()[0]
            b = im.norm.inverse(np.linspace(0, 1, im.cmap.N + 1))
            v = np.linspace(im.norm.vmin, im.norm.vmax, im.cmap.N)
            if matplotlib.__version__ >= '0.91.0':
                cb = f.colorbar(im,
                                ax=ax,
                                orientation='horizontal',
                                shrink=0.5,
                                aspect=25,
                                ticks=PA.BoundaryLocator(),
                                pad=0.05,
                                fraction=0.1,
                                boundaries=b,
                                values=v,
                                format=format)
            else:
                # for older matplotlib versions, no ax kwarg
                cb = f.colorbar(im,
                                orientation='horizontal',
                                shrink=0.5,
                                aspect=25,
                                ticks=PA.BoundaryLocator(),
                                pad=0.05,
                                fraction=0.1,
                                boundaries=b,
                                values=v,
                                format=format)
        ax.set_title(title)
        if not notext:
            ax.text(0.86,
                    0.05,
                    ax.proj.coordsysstr,
                    fontsize=14,
                    fontweight='bold',
                    transform=ax.transAxes)
        if cbar:
            cb.ax.text(0.5,
                       -1.0,
                       unit,
                       fontsize=14,
                       transform=cb.ax.transAxes,
                       ha='center',
                       va='center')
        f.sca(ax)
    finally:
        pylab.draw()
        if wasinteractive:
            pylab.ion()
示例#7
0
def gnomview(map=None,
             fig=None,
             rot=None,
             coord=None,
             unit='',
             xsize=200,
             ysize=None,
             reso=1.5,
             degree=False,
             title='Gnomonic view',
             nest=False,
             remove_dip=False,
             remove_mono=False,
             gal_cut=0,
             min=None,
             max=None,
             flip='astro',
             format='%.3g',
             cbar=True,
             cmap=None,
             norm=None,
             hold=False,
             sub=None,
             margins=None,
             notext=False):
    """Plot an healpix map (given as an array) in Gnomonic projection.

    Parameters
    ----------
    map : array-like
      The map to project, supports masked maps, see the `ma` function.
      If None, use a blank map, useful for
      overplotting.
    fig : None or int, optional
      A figure number. Default: None= create a new figure
    rot : scalar or sequence, optional
      Describe the rotation to apply.
      In the form (lon, lat, psi) (unit: degrees) : the point at
      longitude *lon* and latitude *lat* will be at the center. An additional rotation
      of angle *psi* around this direction is applied.
    coord : sequence of character, optional
      Either one of 'G', 'E' or 'C' to describe the coordinate
      system of the map, or a sequence of 2 of these to rotate
      the map from the first to the second coordinate system.
    unit : str, optional
      A text describing the unit of the data. Default: ''
    xsize : int, optional
      The size of the image. Default: 200
    ysize : None or int, optional
      The size of the image. Default: None= xsize
    reso : float, optional
      Resolution (in arcmin if degree is False). Default: 1.5 arcmin
    degree : bool, optional
      if True, reso is in degree. Default: False
    title : str, optional
      The title of the plot. Default: 'Gnomonic view'
    nest : bool, optional
      If True, ordering scheme is NESTED. Default: False (RING)
    min : float, scalar, optional
      The minimum range value
    max : float, scalar, optional
      The maximum range value
    flip : {'astro', 'geo'}, optional
      Defines the convention of projection : 'astro' (default, east towards left, west towards right)
      or 'geo' (east towards roght, west towards left)
    remove_dip : bool, optional
      If :const:`True`, remove the dipole+monopole
    remove_mono : bool, optional
      If :const:`True`, remove the monopole
    gal_cut : float, scalar, optional
      Symmetric galactic cut for the dipole/monopole fit.
      Removes points in latitude range [-gal_cut, +gal_cut]
    format : str, optional
      The format of the scale label. Default: '%g'
    hold : bool, optional
      If True, replace the current Axes by a MollweideAxes.
      use this if you want to have multiple maps on the same
      figure. Default: False
    sub : int or sequence, optional
      Use only a zone of the current figure (same syntax as subplot).
      Default: None
    margins : None or sequence, optional
      Either None, or a sequence (left,bottom,right,top)
      giving the margins on left,bottom,right and top
      of the axes. Values are relative to figure (0-1).
      Default: None
    notext: bool, optional
      If True: do not add resolution info text. Default=False

    See Also
    --------
    mollview, cartview
    """
    import pylab
    if not (hold or sub):
        f = pylab.figure(fig, figsize=(5.8, 6.4))
        if not margins:
            margins = (0.075, 0.05, 0.075, 0.05)
        extent = (0.0, 0.0, 1.0, 1.0)
    elif hold:
        f = pylab.gcf()
        left, bottom, right, top = np.array(pylab.gca().get_position()).ravel()
        if not margins:
            margins = (0.0, 0.0, 0.0, 0.0)
        extent = (left, bottom, right - left, top - bottom)
        f.delaxes(pylab.gca())
    else:  # using subplot syntax
        f = pylab.gcf()
        if hasattr(sub, '__len__'):
            nrows, ncols, idx = sub
        else:
            nrows, ncols, idx = sub / 100, (sub % 100) / 10, (sub % 10)
        if idx < 1 or idx > ncols * nrows:
            raise ValueError('Wrong values for sub: %d, %d, %d' %
                             (nrows, ncols, idx))
        c, r = (idx - 1) % ncols, (idx - 1) / ncols
        if not margins:
            margins = (0.01, 0.0, 0.0, 0.02)
        extent = (c * 1. / ncols + margins[0],
                  1. - (r + 1) * 1. / nrows + margins[1],
                  1. / ncols - margins[2] - margins[0],
                  1. / nrows - margins[3] - margins[1])
    extent = (extent[0] + margins[0], extent[1] + margins[1],
              extent[2] - margins[2] - margins[0],
              extent[3] - margins[3] - margins[1])
    #f=pylab.figure(fig,figsize=(5.5,6))

    # Starting to draw : turn interactive off
    wasinteractive = pylab.isinteractive()
    pylab.ioff()
    try:
        if map is None:
            map = np.zeros(12) + np.inf
            cbar = False
        map = pixelfunc.ma_to_array(map)
        ax = PA.HpxGnomonicAxes(f,
                                extent,
                                coord=coord,
                                rot=rot,
                                format=format,
                                flipconv=flip)
        f.add_axes(ax)
        if remove_dip:
            map = pixelfunc.remove_dipole(map,
                                          gal_cut=gal_cut,
                                          nest=nest,
                                          copy=True)
        elif remove_mono:
            map = pixelfunc.remove_monopole(map,
                                            gal_cut=gal_cut,
                                            nest=nest,
                                            copy=True)
        ax.projmap(map,
                   nest=nest,
                   coord=coord,
                   vmin=min,
                   vmax=max,
                   xsize=xsize,
                   ysize=ysize,
                   reso=reso,
                   cmap=cmap,
                   norm=norm)
        if cbar:
            im = ax.get_images()[0]
            b = im.norm.inverse(np.linspace(0, 1, im.cmap.N + 1))
            v = np.linspace(im.norm.vmin, im.norm.vmax, im.cmap.N)
            if matplotlib.__version__ >= '0.91.0':
                cb = f.colorbar(im,
                                ax=ax,
                                orientation='horizontal',
                                shrink=0.5,
                                aspect=25,
                                ticks=PA.BoundaryLocator(),
                                pad=0.08,
                                fraction=0.1,
                                boundaries=b,
                                values=v,
                                format=format)
            else:
                cb = f.colorbar(im,
                                orientation='horizontal',
                                shrink=0.5,
                                aspect=25,
                                ticks=PA.BoundaryLocator(),
                                pad=0.08,
                                fraction=0.1,
                                boundaries=b,
                                values=v,
                                format=format)
        ax.set_title(title)
        if not notext:
            ax.text(-0.07,
                    0.02,
                    "%g '/pix,   %dx%d pix" %
                    (ax.proj.arrayinfo['reso'], ax.proj.arrayinfo['xsize'],
                     ax.proj.arrayinfo['ysize']),
                    fontsize=12,
                    verticalalignment='bottom',
                    transform=ax.transAxes,
                    rotation=90)
            ax.text(-0.07,
                    0.6,
                    ax.proj.coordsysstr,
                    fontsize=14,
                    fontweight='bold',
                    rotation=90,
                    transform=ax.transAxes)
            lon, lat = np.around(ax.proj.get_center(lonlat=True),
                                 ax._coordprec)
            ax.text(0.5,
                    -0.03,
                    '(%g,%g)' % (lon, lat),
                    verticalalignment='center',
                    horizontalalignment='center',
                    transform=ax.transAxes)
        if cbar:
            cb.ax.text(1.05,
                       0.30,
                       unit,
                       fontsize=14,
                       fontweight='bold',
                       transform=cb.ax.transAxes,
                       ha='left',
                       va='center')
        f.sca(ax)
    finally:
        pylab.draw()
        if wasinteractive:
            pylab.ion()
示例#8
0
def mollzoom(map=None,fig=None,rot=None,coord=None,unit='',
             xsize=800,title='Mollweide view',nest=False,
             min=None,max=None,flip='astro',
             remove_dip=False,remove_mono=False,
             gal_cut=0,
             format='%g',cmap=None,
             norm=None,hold=False,margins=None,sub=None):
    """Interactive mollweide plot with zoomed gnomview.
    
    Parameters:
    -----------
    map : float, array-like shape (Npix,)
      An array containing the map, 
      supports masked maps, see the `ma` function.
      if None, use map with inf value (white map), useful for
      overplotting
    fig : a figure number. 
      Default: create a new figure
    rot : scalar or sequence, optional
      Describe the rotation to apply.
      In the form (lon, lat, psi) (unit: degrees) : the point at
      longitude *lon* and latitude *lat* will be at the center. An additional rotation
      of angle *psi* around this direction is applied.
    coord : sequence of character, optional
      Either one of 'G', 'E' or 'C' to describe the coordinate
      system of the map, or a sequence of 2 of these to rotate
      the map from the first to the second coordinate system.
    unit : str, optional
      A text describing the unit of the data. Default: ''
    xsize : int, optional
      The size of the image. Default: 800
    title : str, optional
      The title of the plot. Default: 'Mollweide view'
    nest : bool, optional
      If True, ordering scheme is NESTED. Default: False (RING)
    min : float, optional
      The minimum range value
    max : float, optional
      The maximum range value
    flip : {'astro', 'geo'}, optional
      Defines the convention of projection : 'astro' (default, east towards left, west towards right)
      or 'geo' (east towards roght, west towards left)
    remove_dip : bool, optional
      If :const:`True`, remove the dipole+monopole
    remove_mono : bool, optional
      If :const:`True`, remove the monopole
    gal_cut : float, scalar, optional
      Symmetric galactic cut for the dipole/monopole fit.
      Removes points in latitude range [-gal_cut, +gal_cut]
    format : str, optional
      The format of the scale label. Default: '%g'
    """
    import pylab
    # create the figure (if interactive, it will open the window now)
    f=pylab.figure(fig,figsize=(10.5,5.4))
    extent = (0.02,0.25,0.56,0.72)
    # Starting to draw : turn interactive off
    wasinteractive = pylab.isinteractive()
    pylab.ioff()
    try:
        if map is None:
            map = np.zeros(12)+np.inf
        map = pixelfunc.ma_to_array(map)
        ax=PA.HpxMollweideAxes(f,extent,coord=coord,rot=rot,
                               format=format,flipconv=flip)
        f.add_axes(ax)
        if remove_dip:
            map=pixelfunc.remove_dipole(map,gal_cut=gal_cut,
                                        nest=nest,copy=True,
                                        verbose=True)
        elif remove_mono:
            map=pixelfunc.remove_monopole(map,gal_cut=gal_cut,nest=nest,
                                          copy=True,verbose=True)
        ax.projmap(map,nest=nest,xsize=xsize,coord=coord,vmin=min,vmax=max,
                   cmap=cmap,norm=norm)
        im = ax.get_images()[0]
        b = im.norm.inverse(np.linspace(0,1,im.cmap.N+1))
        v = np.linspace(im.norm.vmin,im.norm.vmax,im.cmap.N)
        if matplotlib.__version__ >= '0.91.0':
            cb=f.colorbar(ax.get_images()[0],ax=ax,
                          orientation='horizontal',
                          shrink=0.5,aspect=25,ticks=PA.BoundaryLocator(),
                          pad=0.05,fraction=0.1,boundaries=b,values=v)
        else:
            # for older matplotlib versions, no ax kwarg
            cb=f.colorbar(ax.get_images()[0],orientation='horizontal',
                          shrink=0.5,aspect=25,ticks=PA.BoundaryLocator(),
                          pad=0.05,fraction=0.1,boundaries=b,values=v)
        ax.set_title(title)
        ax.text(0.86,0.05,ax.proj.coordsysstr,fontsize=14,
                fontweight='bold',transform=ax.transAxes)
        cb.ax.text(1.05,0.30,unit,fontsize=14,fontweight='bold',
                   transform=cb.ax.transAxes,ha='left',va='center')
        f.sca(ax)

        ## Gnomonic axes
        #extent = (0.02,0.25,0.56,0.72)
        g_xsize=600
        g_reso = 1.
        extent = (0.60,0.04,0.38,0.94)
        g_ax=PA.HpxGnomonicAxes(f,extent,coord=coord,rot=rot,
                                format=format,flipconv=flip)
        f.add_axes(g_ax)
        if remove_dip:
            map=pixelfunc.remove_dipole(map,gal_cut=gal_cut,nest=nest,copy=True)
        elif remove_mono:
            map=pixelfunc.remove_monopole(map,gal_cut=gal_cut,nest=nest,copy=True)
        g_ax.projmap(map,nest=nest,coord=coord,vmin=min,vmax=max,
                   xsize=g_xsize,ysize=g_xsize,reso=g_reso,cmap=cmap,norm=norm)
        im = g_ax.get_images()[0]
        b = im.norm.inverse(np.linspace(0,1,im.cmap.N+1))
        v = np.linspace(im.norm.vmin,im.norm.vmax,im.cmap.N)
        if matplotlib.__version__ >= '0.91.0':
            cb=f.colorbar(g_ax.get_images()[0],ax=g_ax,
                          orientation='horizontal',
                          shrink=0.5,aspect=25,ticks=PA.BoundaryLocator(),
                          pad=0.08,fraction=0.1,boundaries=b,values=v)
        else:
            cb=f.colorbar(g_ax.get_images()[0],orientation='horizontal',
                          shrink=0.5,aspect=25,ticks=PA.BoundaryLocator(),
                          pad=0.08,fraction=0.1,boundaries=b,values=v)
        g_ax.set_title(title)
        g_ax.text(-0.07,0.02,
                   "%g '/pix,   %dx%d pix"%(g_ax.proj.arrayinfo['reso'],
                                            g_ax.proj.arrayinfo['xsize'],
                                            g_ax.proj.arrayinfo['ysize']),
                   fontsize=12,verticalalignment='bottom',
                   transform=g_ax.transAxes,rotation=90)
        g_ax.text(-0.07,0.8,g_ax.proj.coordsysstr,fontsize=14,
                   fontweight='bold',rotation=90,transform=g_ax.transAxes)
        lon,lat = np.around(g_ax.proj.get_center(lonlat=True),g_ax._coordprec)
        g_ax.text(0.5,-0.03,'on (%g,%g)'%(lon,lat),
                  verticalalignment='center', horizontalalignment='center',
                  transform=g_ax.transAxes)
        cb.ax.text(1.05,0.30,unit,fontsize=14,fontweight='bold',
                   transform=cb.ax.transAxes,ha='left',va='center')
        # Add graticule info axes
        grat_ax = pylab.axes([0.25, 0.02, 0.22,0.25])
        grat_ax.axis('off')
        # Add help text
        help_ax = pylab.axes([0.02,0.02,0.22,0.25])
        help_ax.axis('off')
        t = help_ax.transAxes
        help_ax.text(0.1, 0.8, 'r/t .... zoom out/in',transform=t,va='baseline')
        help_ax.text(0.1, 0.65,'p/v .... print coord/val',transform=t,va='baseline')
        help_ax.text(0.1, 0.5, 'c ...... go to center',transform=t,va='baseline')
        help_ax.text(0.1, 0.35,'f ...... next color scale',transform=t,va='baseline')
        help_ax.text(0.1, 0.2, 'k ...... save current scale',transform=t,
                     va='baseline')
        help_ax.text(0.1, 0.05,'g ...... toggle graticule',transform=t,va='baseline')
        f.sca(g_ax)
        # Set up the zoom capability
        zt=ZoomTool(map,fig=f.number,nest=nest,cmap=cmap,norm=norm,coord=coord)
    finally:
        pylab.draw()
        if wasinteractive:
            pylab.ion()
示例#9
0
def mollzoom(map=None,
             fig=None,
             rot=None,
             coord=None,
             unit='',
             xsize=800,
             title='Mollweide view',
             nest=False,
             min=None,
             max=None,
             flip='astro',
             remove_dip=False,
             remove_mono=False,
             gal_cut=0,
             format='%g',
             cmap=None,
             norm=None,
             hold=False,
             margins=None,
             sub=None):
    """Interactive mollweide plot with zoomed gnomview.
    
    Parameters:
    -----------
    map : float, array-like shape (Npix,)
      An array containing the map, 
      supports masked maps, see the `ma` function.
      if None, use map with inf value (white map), useful for
      overplotting
    fig : a figure number. 
      Default: create a new figure
    rot : scalar or sequence, optional
      Describe the rotation to apply.
      In the form (lon, lat, psi) (unit: degrees) : the point at
      longitude *lon* and latitude *lat* will be at the center. An additional rotation
      of angle *psi* around this direction is applied.
    coord : sequence of character, optional
      Either one of 'G', 'E' or 'C' to describe the coordinate
      system of the map, or a sequence of 2 of these to rotate
      the map from the first to the second coordinate system.
    unit : str, optional
      A text describing the unit of the data. Default: ''
    xsize : int, optional
      The size of the image. Default: 800
    title : str, optional
      The title of the plot. Default: 'Mollweide view'
    nest : bool, optional
      If True, ordering scheme is NESTED. Default: False (RING)
    min : float, optional
      The minimum range value
    max : float, optional
      The maximum range value
    flip : {'astro', 'geo'}, optional
      Defines the convention of projection : 'astro' (default, east towards left, west towards right)
      or 'geo' (east towards roght, west towards left)
    remove_dip : bool, optional
      If :const:`True`, remove the dipole+monopole
    remove_mono : bool, optional
      If :const:`True`, remove the monopole
    gal_cut : float, scalar, optional
      Symmetric galactic cut for the dipole/monopole fit.
      Removes points in latitude range [-gal_cut, +gal_cut]
    format : str, optional
      The format of the scale label. Default: '%g'
    """
    import pylab
    # create the figure (if interactive, it will open the window now)
    f = pylab.figure(fig, figsize=(10.5, 5.4))
    extent = (0.02, 0.25, 0.56, 0.72)
    # Starting to draw : turn interactive off
    wasinteractive = pylab.isinteractive()
    pylab.ioff()
    try:
        if map is None:
            map = np.zeros(12) + np.inf
        map = pixelfunc.ma_to_array(map)
        ax = PA.HpxMollweideAxes(f,
                                 extent,
                                 coord=coord,
                                 rot=rot,
                                 format=format,
                                 flipconv=flip)
        f.add_axes(ax)
        if remove_dip:
            map = pixelfunc.remove_dipole(map,
                                          gal_cut=gal_cut,
                                          nest=nest,
                                          copy=True,
                                          verbose=True)
        elif remove_mono:
            map = pixelfunc.remove_monopole(map,
                                            gal_cut=gal_cut,
                                            nest=nest,
                                            copy=True,
                                            verbose=True)
        ax.projmap(map,
                   nest=nest,
                   xsize=xsize,
                   coord=coord,
                   vmin=min,
                   vmax=max,
                   cmap=cmap,
                   norm=norm)
        im = ax.get_images()[0]
        b = im.norm.inverse(np.linspace(0, 1, im.cmap.N + 1))
        v = np.linspace(im.norm.vmin, im.norm.vmax, im.cmap.N)
        if matplotlib.__version__ >= '0.91.0':
            cb = f.colorbar(ax.get_images()[0],
                            ax=ax,
                            orientation='horizontal',
                            shrink=0.5,
                            aspect=25,
                            ticks=PA.BoundaryLocator(),
                            pad=0.05,
                            fraction=0.1,
                            boundaries=b,
                            values=v)
        else:
            # for older matplotlib versions, no ax kwarg
            cb = f.colorbar(ax.get_images()[0],
                            orientation='horizontal',
                            shrink=0.5,
                            aspect=25,
                            ticks=PA.BoundaryLocator(),
                            pad=0.05,
                            fraction=0.1,
                            boundaries=b,
                            values=v)
        ax.set_title(title)
        ax.text(0.86,
                0.05,
                ax.proj.coordsysstr,
                fontsize=14,
                fontweight='bold',
                transform=ax.transAxes)
        cb.ax.text(1.05,
                   0.30,
                   unit,
                   fontsize=14,
                   fontweight='bold',
                   transform=cb.ax.transAxes,
                   ha='left',
                   va='center')
        f.sca(ax)

        ## Gnomonic axes
        #extent = (0.02,0.25,0.56,0.72)
        g_xsize = 600
        g_reso = 1.
        extent = (0.60, 0.04, 0.38, 0.94)
        g_ax = PA.HpxGnomonicAxes(f,
                                  extent,
                                  coord=coord,
                                  rot=rot,
                                  format=format,
                                  flipconv=flip)
        f.add_axes(g_ax)
        if remove_dip:
            map = pixelfunc.remove_dipole(map,
                                          gal_cut=gal_cut,
                                          nest=nest,
                                          copy=True)
        elif remove_mono:
            map = pixelfunc.remove_monopole(map,
                                            gal_cut=gal_cut,
                                            nest=nest,
                                            copy=True)
        g_ax.projmap(map,
                     nest=nest,
                     coord=coord,
                     vmin=min,
                     vmax=max,
                     xsize=g_xsize,
                     ysize=g_xsize,
                     reso=g_reso,
                     cmap=cmap,
                     norm=norm)
        im = g_ax.get_images()[0]
        b = im.norm.inverse(np.linspace(0, 1, im.cmap.N + 1))
        v = np.linspace(im.norm.vmin, im.norm.vmax, im.cmap.N)
        if matplotlib.__version__ >= '0.91.0':
            cb = f.colorbar(g_ax.get_images()[0],
                            ax=g_ax,
                            orientation='horizontal',
                            shrink=0.5,
                            aspect=25,
                            ticks=PA.BoundaryLocator(),
                            pad=0.08,
                            fraction=0.1,
                            boundaries=b,
                            values=v)
        else:
            cb = f.colorbar(g_ax.get_images()[0],
                            orientation='horizontal',
                            shrink=0.5,
                            aspect=25,
                            ticks=PA.BoundaryLocator(),
                            pad=0.08,
                            fraction=0.1,
                            boundaries=b,
                            values=v)
        g_ax.set_title(title)
        g_ax.text(-0.07,
                  0.02,
                  "%g '/pix,   %dx%d pix" %
                  (g_ax.proj.arrayinfo['reso'], g_ax.proj.arrayinfo['xsize'],
                   g_ax.proj.arrayinfo['ysize']),
                  fontsize=12,
                  verticalalignment='bottom',
                  transform=g_ax.transAxes,
                  rotation=90)
        g_ax.text(-0.07,
                  0.8,
                  g_ax.proj.coordsysstr,
                  fontsize=14,
                  fontweight='bold',
                  rotation=90,
                  transform=g_ax.transAxes)
        lon, lat = np.around(g_ax.proj.get_center(lonlat=True),
                             g_ax._coordprec)
        g_ax.text(0.5,
                  -0.03,
                  'on (%g,%g)' % (lon, lat),
                  verticalalignment='center',
                  horizontalalignment='center',
                  transform=g_ax.transAxes)
        cb.ax.text(1.05,
                   0.30,
                   unit,
                   fontsize=14,
                   fontweight='bold',
                   transform=cb.ax.transAxes,
                   ha='left',
                   va='center')
        # Add graticule info axes
        grat_ax = pylab.axes([0.25, 0.02, 0.22, 0.25])
        grat_ax.axis('off')
        # Add help text
        help_ax = pylab.axes([0.02, 0.02, 0.22, 0.25])
        help_ax.axis('off')
        t = help_ax.transAxes
        help_ax.text(0.1,
                     0.8,
                     'r/t .... zoom out/in',
                     transform=t,
                     va='baseline')
        help_ax.text(0.1,
                     0.65,
                     'p/v .... print coord/val',
                     transform=t,
                     va='baseline')
        help_ax.text(0.1,
                     0.5,
                     'c ...... go to center',
                     transform=t,
                     va='baseline')
        help_ax.text(0.1,
                     0.35,
                     'f ...... next color scale',
                     transform=t,
                     va='baseline')
        help_ax.text(0.1,
                     0.2,
                     'k ...... save current scale',
                     transform=t,
                     va='baseline')
        help_ax.text(0.1,
                     0.05,
                     'g ...... toggle graticule',
                     transform=t,
                     va='baseline')
        f.sca(g_ax)
        # Set up the zoom capability
        zt = ZoomTool(map,
                      fig=f.number,
                      nest=nest,
                      cmap=cmap,
                      norm=norm,
                      coord=coord)
    finally:
        pylab.draw()
        if wasinteractive:
            pylab.ion()