示例#1
0
def plot_vel_map_panels(vel_list, header=None, contour_image=None,
        limits=None, contours=None, filename=None, show=False,
        vel_vlimits=[None,None], vscale='linear'):

    # Import external modules
    import matplotlib.pyplot as plt
    import matplotlib
    import numpy as np
    import matplotlib.pyplot as plt
    import myplotting as myplt
    import pywcsgrid2 as wcs
    import pywcs
    from pylab import cm # colormaps
    from matplotlib.patches import Polygon
    from mpl_toolkits.axes_grid1 import AxesGrid

    # Set up plot aesthetics
    plt.clf(); plt.close()

    # Color map
    cmap = plt.cm.gnuplot
    #cmap = myplt.reverse_colormap(plt.cm.copper)
    cmap = plt.cm.BrBG
    cmap = plt.cm.winter

    #
    ngrids = len(vel_list)
    nrows, ncols = myplt.get_square_grid_sides(ngrids)
    nrows, ncols = 1, len(vel_list)
    nrows_ncols = (nrows, ncols)

    # Create figure instance
    fig = plt.figure(figsize=(3 * ncols + 1, 3 * nrows + 1))

    #grid_helper = wcs.GridHelper(wcs=header)
    axes = AxesGrid(fig, (1,1,1),
                 nrows_ncols=nrows_ncols,
                 ngrids=ngrids,
                 cbar_mode="single",
                 cbar_location='right',
                 cbar_pad="2%",
                 cbar_size='7%',
                 axes_pad=0.3,
                 #axes_class=(wcs.Axes,
                 #            dict(grid_helper=grid_helper)),
                 axes_class=(wcs.Axes,
                             dict(header=header)),
                 aspect=True,
                 label_mode='L',
                 share_all=True)


    for i in xrange(ngrids):
        # create axes
        ax = axes[i]

        if vscale == 'log':
            norm = matplotlib.colors.LogNorm()
            vel_list[i][vel_list[i] <= 0] = np.nan
            if 0 in vel_vlimits:
                vel_vlimits = [None, None]
        else:
            norm = None

        # show the image
        im = ax.imshow(vel_list[i],
                       #interpolation='nearest',
                       origin='lower',
                       cmap=cmap,
                       vmin=vel_vlimits[0],
                       vmax=vel_vlimits[1],
                       norm=norm,
                       #norm=matplotlib.colors.LogNorm()
                       )

        # Asthetics
        ax.set_display_coord_system("gal")
        #ax.set_ticklabel_type("hms", "dms")
        ax.set_ticklabel_type("absdeg", "absdeg")

        #ax.set_xlabel('Right Ascension [J2000]',)
        #ax.set_ylabel('Declination [J2000]',)
        ax.set_xlabel(r'$l$ [deg]',)
        ax.set_ylabel(r'$b$ [deg]',)
        ax.tick_params(axis='xy', which='major', colors='w')
        ax.locator_params(nbins=4)
        #ax.tick_params(colors='w')

        # colorbar
        cb = ax.cax.colorbar(im)
        cmap.set_bad(color='w')

        # plot limits
        if limits is not None:
            limits_pix = myplt.convert_wcs_limits(limits,
                                                  header,
                                                  frame='galactic')
            ax.set_xlim(limits_pix[0],limits_pix[1])
            ax.set_ylim(limits_pix[2],limits_pix[3])

        # Plot Av contours
        if contour_image is not None:
            ax.contour(contour_image, levels=contours, colors='r')

        # Write label to colorbar
        cb.set_label_text(r'Velocity [km/s]',)

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight')
    if show:
        plt.show()
def plot_diffuseLOS_map(header=None,
                        av_image=None,
                        df=None,
                        core_dict=None,
                        limits=None,
                        filename=None,
                        vlimits=(None, None),
                        contours=None,
                        parameter='phi_cnm',
                        models=['krumholz', 'sternberg']):

    # Import external modules
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import AxesGrid
    import pywcsgrid2 as wcs
    from matplotlib.patches import Polygon
    import matplotlib.patheffects as PathEffects
    import myplotting as myplt

    # Set up plot aesthetics
    # ----------------------
    #plt.close;plt.clf()

    # Color map
    cmap = plt.cm.copper

    # Color cycle, grabs colors from cmap
    color_cycle = [cmap(i) for i in np.linspace(0, 0.8, 2)]
    font_scale = 9

    # Create figure instance
    fig = plt.figure(figsize=(3.6, 10))

    if 0:
        parameters = []
        #if 'krumholz' in models:
        #    parameters.append('phi_cnm', 'alphaG', 'hi_transition', 'n_H', 'T_H']

    parameters = [
        'fraction_diffuse',
    ]

    ngrids = len(parameters)
    nrows_ncols = (ngrids, 1)
    axesgrid = AxesGrid(fig, (1, 1, 1),
                        nrows_ncols=nrows_ncols,
                        ngrids=ngrids,
                        cbar_mode="each",
                        cbar_location='top',
                        cbar_pad="2%",
                        cbar_size='6%',
                        axes_pad=0.1,
                        axes_class=(wcs.Axes, dict(header=header)),
                        aspect=True,
                        label_mode='L',
                        share_all=False)

    # ------------------
    # Av image
    # ------------------
    for i in xrange(ngrids):
        # create axes
        ax = axesgrid[i]
        # show the image
        X, Y = np.meshgrid(np.arange(av_image.shape[1]),
                           np.arange(av_image.shape[0]))

        im = ax.contour(
            X,
            Y,
            av_image,
            origin='lower',
            levels=contours,
            cmap=myplt.truncate_colormap(
                plt.cm.binary,
                minval=0.3,
            )
            #vmin=vlimits[0],
            #vmax=vlimits[1],
            #norm=matplotlib.colors.LogNorm()
        )

        # Asthetics
        ax.set_display_coord_system("fk5")
        ax.set_ticklabel_type("hms", "dms")

        ax.set_xlabel('Right Ascension [J2000]', )
        ax.set_ylabel('Declination [J2000]', )

        ax.locator_params(nbins=4)

        # plot limits
        if limits is not None:
            limits_pix = myplt.convert_wcs_limits(limits, header)
            ax.set_xlim(limits_pix[0], limits_pix[1])
            ax.set_ylim(limits_pix[2], limits_pix[3])

        # Plot cores for each cloud
        # -------------------------
        from matplotlib.patches import Circle
        from matplotlib.collections import PatchCollection

        parameter = parameters[i]
        patches = get_patches(df, header)
        cmap = myplt.truncate_colormap(plt.cm.copper, minval=0.1, maxval=1.0)
        collection = PatchCollection(
            patches,
            cmap=cmap,
            edgecolors='k',
            linewidth=0.75,
            zorder=1000,
        )

        # set values in collection
        collection_values = []
        if parameter in [
                'fraction_diffuse',
        ]:
            collection.set_array(df[parameter])
        else:
            for core in df['core']:
                collection_values.append(core_dict[core][parameter])

            collection.set_array(np.array(collection_values))

        ax.add_collection(collection, )

        # colorbar
        #cbar = axesgrid.cbar_axes[i].colorbar(collection)
        cbar = ax.cax.colorbar(collection)
        if parameter == 'fraction_diffuse':
            cbar.set_label_text(r'Fraction of Diffuse LOS', )

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight', dpi=600)
示例#3
0
def plot_nhi_maps(nhi_1, nhi_2, header=None, contour_image=None,
        limits=None, contours=None, filename=None, show=False,
        nhi_1_vlimits=[None,None], nhi_2_vlimits=[None,None], vscale='linear'):

    # Import external modules
    import matplotlib.pyplot as plt
    import matplotlib
    import numpy as np
    import astropy.io as fits
    import matplotlib.pyplot as plt
    import myplotting as myplt
    import pywcsgrid2 as wcs
    import pywcs
    from pylab import cm # colormaps
    from matplotlib.patches import Polygon
    from mpl_toolkits.axes_grid1 import AxesGrid

    # Import external modules
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import AxesGrid
    import pywcsgrid2 as wcs
    from matplotlib.patches import Polygon
    import matplotlib.patheffects as PathEffects
    import myplotting as myplt

    # Set up plot aesthetics
    plt.clf(); plt.close()

    # Color map
    cmap = plt.cm.gnuplot
    #cmap = myplt.reverse_colormap(plt.cm.copper)
    cmap = plt.cm.copper_r
    cmap = plt.cm.gist_heat_r

    # Create figure instance
    fig = plt.figure(figsize=(3, 4))

    if nhi_2 is not None:
        nrows_ncols=(1,2)
        ngrids=2
    else:
        nrows_ncols=(1,1)
        ngrids=1

    #grid_helper = wcs.GridHelper(wcs=header)
    axes = AxesGrid(fig, (1,1,1),
                 nrows_ncols=nrows_ncols,
                 ngrids=ngrids,
                 cbar_mode="single",
                 cbar_location='right',
                 cbar_pad="3%",
                 cbar_size='7%',
                 axes_pad=0.1,
                 axes_class=(wcs.Axes,
                             #dict(grid_helper=grid_helper)),
                             dict(header=header)),
                 aspect=True,
                 label_mode='L',
                 share_all=True)

    if vscale == 'log':
        norm = matplotlib.colors.LogNorm()
        nhi_1[nhi_1 <= 0] = np.nan
        nhi_2[nhi_2 <= 0] = np.nan
        if 0 in nhi_1_vlimits:
            nhi_1_vlimits = [None, None]
        if 0 in nhi_2_vlimits:
            nhi_2_vlimits = [None, None]
    else:
        norm = None

    # ------------------
    # NHI image
    # ------------------
    # create axes
    ax = axes[0]

    # show the image
    im = ax.imshow(nhi_1,
            interpolation='none',
            origin='lower',
            cmap=cmap,
            vmin=nhi_1_vlimits[0],
            vmax=nhi_1_vlimits[1],
            norm=norm,
            #norm=matplotlib.colors.LogNorm()
            )

    # Asthetics
    ax.set_display_coord_system("gal")
    #ax.set_ticklabel_type("hms", "dms")
    ax.set_ticklabel_type("absdeg", "absdeg")

    #ax.set_xlabel('Right Ascension [J2000]',)
    #ax.set_ylabel('Declination [J2000]',)
    ax.set_xlabel('Glong',)
    ax.set_ylabel('Glat',)


    # colorbar
    cb = ax.cax.colorbar(im)
    cmap.set_bad(color='w')
    #ax.tick_params(colors='w')
    ax.locator_params(nbins=4)
    #ax.tick_params(colors='w')

    # plot limits
    if limits is not None:
        limits_pix = myplt.convert_wcs_limits(limits,
                                              header,
                                              frame='galactic')
        ax.set_xlim(limits_pix[0],limits_pix[1])
        ax.set_ylim(limits_pix[2],limits_pix[3])

    # Plot Av contours
    if contour_image is not None:
        ax.contour(contour_image, levels=contours, colors='r')

    # Write label to colorbar
    cb.set_label_text(r'$N$(H\textsc{i}) [10$^{20}$ cm$^{-2}$]',)

    # ------------------
    # Av image
    # ------------------
    if nhi_2 is not None:
        # create axes
        ax = axes[1]
        # show the image
        im = ax.imshow(nhi_2,
                interpolation='none',
                origin='lower',
                cmap=cmap,
                vmin=nhi_2_vlimits[0],
                vmax=nhi_2_vlimits[1],
                norm=norm
                )

        # Asthetics
        ax.set_display_coord_system("gal")
        #ax.set_ticklabel_type("hms", "dms")
        ax.set_ticklabel_type("absdeg", "absdeg")

        #ax.set_xlabel('Right Ascension [J2000]',)
        #ax.set_ylabel('Declination [J2000]',)
        ax.set_xlabel('Glong',)
        ax.set_ylabel('Glat',)

        ax.locator_params(nbins=4)
        #ax.tick_params(colors='w')

        # colorbar
        cb = ax.cax.colorbar(im)
        cmap.set_bad(color='w')

        # plot limits
        if limits is not None:
            limits_pix = myplt.convert_wcs_limits(limits,
                                                  header,
                                                  frame='galactic')
            ax.set_xlim(limits_pix[0],limits_pix[1])
            ax.set_ylim(limits_pix[2],limits_pix[3])

        ax.tick_params(axis='xy', which='major', colors='w')

        # Plot Av contours
        if contour_image is not None:
            ax.contour(contour_image, levels=contours, colors='r')

        # Write label to colorbar
        cb.set_label_text(r'$N$(H\textsc{i}) [10$^{20}$ cm$^{-2}$]',)

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight')
    if show:
        plt.show()
def plot_rad_map(header=None, contour_image=None, rad_field=None, cores=None,
        cores_to_keep=None,
        props=None, cloud_dict=None, regions=None, title=None, limits=None,
        contours=None, boxes=False, savedir='./', filename=None, show=False,
        hi_vlimits=None, vlimits=None, vscale='linear'):

    # Import external modules
    import matplotlib.pyplot as plt
    import matplotlib
    import numpy as np
    from mpl_toolkits.axes_grid1 import AxesGrid
    import pyfits as pf
    import matplotlib.pyplot as plt
    import pywcsgrid2 as wcs
    import pywcs
    from pylab import cm # colormaps
    from matplotlib.patches import Polygon
    import matplotlib.patheffects as PathEffects
    import myplotting as myplt

    # Set up plot aesthetics
    # ----------------------
    #plt.close();plt.clf()

    # Color map
    cmap = plt.cm.copper

    # Color cycle, grabs colors from cmap

    # Create figure instance
    fig = plt.figure(figsize=(7.5, 5))

    if rad_field is not None:
        nrows_ncols=(1,1)
        ngrids=1

    imagegrid = AxesGrid(fig, (1,1,1),
                 nrows_ncols=nrows_ncols,
                 ngrids=ngrids,
                 cbar_mode="single",
                 cbar_location='right',
                 cbar_pad="2%",
                 cbar_size='3%',
                 axes_pad=0.1,
                 axes_class=(wcs.Axes,
                             dict(header=header)),
                 aspect=True,
                 label_mode='L',
                 share_all=True)

    # ------------------
    # Av image
    # ------------------
    # create axes
    ax = imagegrid[0]


    #ax = wcs.subplot(111, header=header)


    if vscale == 'log':
        norm = matplotlib.colors.LogNorm()
    else:
        norm = None

    # show the image
    im = ax.imshow(rad_field,
            interpolation='nearest',
            origin='lower',
            cmap=cmap,
            norm=norm,
            vmin=vlimits[0],
            vmax=vlimits[1],
            )

    # Asthetics
    #ax.set_display_coord_system("fk5")
    #ax.set_ticklabel_type("hms", "dms")

    #ax.set_xlabel('Right Ascension [J2000]',)
    #ax.set_ylabel('Declination [J2000]',)

    ax.set_display_coord_system("gal")
    #ax.set_ticklabel_type("hms", "dms")
    ax.set_ticklabel_type("dms", "dms")

    #ax.set_xlabel('Right Ascension [J2000]',)
    #ax.set_ylabel('Declination [J2000]',)
    ax.set_xlabel('Galactic Longitude [deg]',)
    ax.set_ylabel('Galactic Latitude [deg]',)
    ax.axis["top",].toggle(ticklabels=True)
    ax.grid(color='w', linewidth=0.5)
    ax.axis[:].major_ticks.set_color("w")

    cmap.set_bad(color='w')

    #ax.locator_params(nbins=6)
    ax.locator_params(nbins=6)

    # colorbar
    from matplotlib.ticker import LogFormatter
    formatter = LogFormatter(10, labelOnlyBase=False)
    ticks = np.logspace(np.log10(vlimits[0]),
                                 np.log10(vlimits[1]),
                                 #np.log10(vlimits[1]) - np.log10(vlimits[0]),
                                 5,
                        )

    from matplotlib.ticker import LogFormatterMathtext

    if 1:
        cb = ax.cax.colorbar(im,
                             #ticks=ticks,
                             #format=LogFormatterMathtext(),
                             )
        #cb.set_label_text(r'log$_{10}$[$U_{0,M83}$]',)
        cb.set_label_text(r'$U\,[U_{\rm D78}$]',)
    else:
        from mpl_toolkits.axes_grid1 import make_axes_locatable
        divider = make_axes_locatable(ax)
        #cax = divider.append_axes("right", size="5%", pad=0.05)

        #plt.colorbar(im, cax=cax)

        #cb = fig.colorbar(im, ax=ax)
        #cb.ax.set_ylabel(r'$U_{0,M83}$',)

    # plot limits
    if limits is not None:
        limits_pix = myplt.convert_wcs_limits(limits, header, frame='fk5')
        ax.set_xlim(limits_pix[0],limits_pix[1])
        ax.set_ylim(limits_pix[2],limits_pix[3])

    # Plot Av contours
    if contour_image is not None:
        ax.contour(contour_image, levels=contours, colors='r')

        if props is not None:
            if 0:
                for region in props['region_name_pos']:
                    if region == 'taurus1':
                        region = 'taurus 1'
                    if region == 'taurus2':
                        region = 'taurus 2'
                    ax.annotate(region.capitalize(),
                                xy=props['region_name_pos'][region]['pixel'],
                                xytext=(0,0),
                                textcoords='offset points',
                                color='w',
                                fontsize=7,
                                zorder=10)

    if regions is not None:
        for region in props['region_name_pos']:
            vertices = np.copy(regions[region]['poly_verts']['pixel'])
            rect = ax.add_patch(Polygon(
                    vertices[:, ::-1],
                    facecolor='none',
                    edgecolor='w'))

   # ax.legend(rects, core_labels, bbox_to_anchor=(1.05, 1), loc=2,
   #         borderaxespad=0.)
    #ax.legend(rects, core_labels, bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
    #       ncol=5, mode="expand", borderaxespad=0.)

    if filename is not None:
        plt.savefig(savedir + filename, bbox_inches='tight')
    if show:
        fig.show()
def plot_params_map(header=None,
                    av_image=None,
                    df=None,
                    limits=None,
                    filename=None,
                    vlimits=(None, None),
                    contours=None,
                    parameter='phi_cnm'):

    # Import external modules
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import AxesGrid
    import pywcsgrid2 as wcs
    from matplotlib.patches import Polygon
    import matplotlib.patheffects as PathEffects
    import myplotting as myplt

    # Set up plot aesthetics
    # ----------------------
    #plt.close;plt.clf()

    # Color map
    cmap = plt.cm.copper

    # Color cycle, grabs colors from cmap
    color_cycle = [cmap(i) for i in np.linspace(0, 0.8, 2)]
    font_scale = 9

    # Create figure instance
    fig = plt.figure(figsize=(3.6, 5))

    nrows_ncols = (3, 1)
    ngrids = 3
    axesgrid = AxesGrid(fig, (1, 1, 1),
                        nrows_ncols=nrows_ncols,
                        ngrids=ngrids,
                        cbar_mode="each",
                        cbar_location='right',
                        cbar_pad="2%",
                        cbar_size='3%',
                        axes_pad=0.1,
                        axes_class=(wcs.Axes, dict(header=header)),
                        aspect=True,
                        label_mode='L',
                        share_all=False)

    # ------------------
    # Av image
    # ------------------
    parameters = ['phi_cnm', 'alphaG', 'hi_transition']
    for i in xrange(ngrids):
        # create axes
        ax = axesgrid[i]
        # show the image
        X, Y = np.meshgrid(np.arange(av_image.shape[1]),
                           np.arange(av_image.shape[0]))

        im = ax.contour(
            X,
            Y,
            av_image,
            origin='lower',
            levels=contours,
            cmap=myplt.truncate_colormap(
                plt.cm.binary,
                minval=0.3,
            )
            #vmin=vlimits[0],
            #vmax=vlimits[1],
            #norm=matplotlib.colors.LogNorm()
        )

        # Asthetics
        ax.set_display_coord_system("fk5")
        ax.set_ticklabel_type("hms", "dms")

        ax.set_xlabel('Right Ascension [J2000]', )
        ax.set_ylabel('Declination [J2000]', )

        ax.locator_params(nbins=4)

        # plot limits
        if limits is not None:
            limits_pix = myplt.convert_wcs_limits(limits, header)
            ax.set_xlim(limits_pix[0], limits_pix[1])
            ax.set_ylim(limits_pix[2], limits_pix[3])

        # Plot cores for each cloud
        # -------------------------
        from matplotlib.patches import Circle
        from matplotlib.collections import PatchCollection

        parameter = parameters[i]
        patches = get_patches(df, header)
        cmap = myplt.truncate_colormap(plt.cm.copper, minval=0.1, maxval=1.0)
        collection = PatchCollection(
            patches,
            cmap=cmap,
            edgecolors='none',
            zorder=1000,
        )

        collection.set_array(df[parameter])
        ax.add_collection(collection, )

        # colorbar
        #cbar = axesgrid.cbar_axes[i].colorbar(collection)
        cbar = ax.cax.colorbar(collection)
        if parameter == 'phi_cnm':
            cbar.set_label_text(r'$\phi_{\rm CNM}$', )
        elif parameter == 'alphaG':
            cbar.set_label_text(r'$\alpha G$', )
        elif parameter == 'hi_transition':
            cbar.set_label_text(r'$\Sigma_{\rm HI,trans}$ ' + \
                                r'$[M_\odot\,{\rm pc}^{-2}]$',)

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight', dpi=100)
def plot_params_map(header=None, av_image=None, df=None, limits=None,
        filename=None, vlimits=(None,None), contours=None, parameter='phi_cnm'):

    # Import external modules
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import AxesGrid
    import pywcsgrid2 as wcs
    from matplotlib.patches import Polygon
    import matplotlib.patheffects as PathEffects
    import myplotting as myplt

    # Set up plot aesthetics
    # ----------------------
    #plt.close;plt.clf()

    # Color map
    cmap = plt.cm.copper

    # Color cycle, grabs colors from cmap
    color_cycle = [cmap(i) for i in np.linspace(0, 0.8, 2)]
    font_scale = 9

    # Create figure instance
    fig = plt.figure(figsize=(3.6, 5))

    nrows_ncols=(3,1)
    ngrids=3
    axesgrid = AxesGrid(fig, (1,1,1),
                 nrows_ncols=nrows_ncols,
                 ngrids=ngrids,
                 cbar_mode="each",
                 cbar_location='right',
                 cbar_pad="2%",
                 cbar_size='3%',
                 axes_pad=0.1,
                 axes_class=(wcs.Axes,
                             dict(header=header)),
                 aspect=True,
                 label_mode='L',
                 share_all=False)

    # ------------------
    # Av image
    # ------------------
    parameters = ['phi_cnm', 'alphaG', 'hi_transition']
    for i in xrange(ngrids):
        # create axes
        ax = axesgrid[i]
        # show the image
        X, Y = np.meshgrid(np.arange(av_image.shape[1]),
                           np.arange(av_image.shape[0]))

        im = ax.contour(X, Y, av_image,
                origin='lower',
                levels=contours,
                cmap=myplt.truncate_colormap(plt.cm.binary, minval=0.3,)
                #vmin=vlimits[0],
                #vmax=vlimits[1],
                #norm=matplotlib.colors.LogNorm()
                )

        # Asthetics
        ax.set_display_coord_system("fk5")
        ax.set_ticklabel_type("hms", "dms")

        ax.set_xlabel('Right Ascension [J2000]',)
        ax.set_ylabel('Declination [J2000]',)

        ax.locator_params(nbins=4)

        # plot limits
        if limits is not None:
            limits_pix = myplt.convert_wcs_limits(limits, header)
            ax.set_xlim(limits_pix[0],limits_pix[1])
            ax.set_ylim(limits_pix[2],limits_pix[3])

        # Plot cores for each cloud
        # -------------------------
        from matplotlib.patches import Circle
        from matplotlib.collections import PatchCollection

        parameter = parameters[i]
        patches = get_patches(df, header)
        cmap = myplt.truncate_colormap(plt.cm.copper, minval=0.1, maxval=1.0)
        collection = PatchCollection(patches,
                                     cmap=cmap,
                                     edgecolors='none',
                                     zorder=1000,
                                     )

        collection.set_array(df[parameter])
        ax.add_collection(collection,
                          )

        # colorbar
        #cbar = axesgrid.cbar_axes[i].colorbar(collection)
        cbar = ax.cax.colorbar(collection)
        if parameter == 'phi_cnm':
            cbar.set_label_text(r'$\phi_{\rm CNM}$',)
        elif parameter == 'alphaG':
            cbar.set_label_text(r'$\alpha G$',)
        elif parameter == 'hi_transition':
            cbar.set_label_text(r'$\Sigma_{\rm HI,trans}$ ' + \
                                r'$[M_\odot\,{\rm pc}^{-2}]$',)

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight', dpi=100)
def plot_diffuseLOS_map(header=None, av_image=None, df=None, core_dict=None,
        limits=None, filename=None, vlimits=(None,None), contours=None,
        parameter='phi_cnm', models=['krumholz', 'sternberg']):

    # Import external modules
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import AxesGrid
    import pywcsgrid2 as wcs
    from matplotlib.patches import Polygon
    import matplotlib.patheffects as PathEffects
    import myplotting as myplt

    # Set up plot aesthetics
    # ----------------------
    #plt.close;plt.clf()

    # Color map
    cmap = plt.cm.copper

    # Color cycle, grabs colors from cmap
    color_cycle = [cmap(i) for i in np.linspace(0, 0.8, 2)]
    font_scale = 9

    # Create figure instance
    fig = plt.figure(figsize=(3.6, 10))


    if 0:
        parameters = []
        #if 'krumholz' in models:
        #    parameters.append('phi_cnm', 'alphaG', 'hi_transition', 'n_H', 'T_H']

    parameters = ['fraction_diffuse',]

    ngrids=len(parameters)
    nrows_ncols=(ngrids,1)
    axesgrid = AxesGrid(fig, (1,1,1),
                 nrows_ncols=nrows_ncols,
                 ngrids=ngrids,
                 cbar_mode="each",
                 cbar_location='top',
                 cbar_pad="2%",
                 cbar_size='6%',
                 axes_pad=0.1,
                 axes_class=(wcs.Axes,
                             dict(header=header)),
                 aspect=True,
                 label_mode='L',
                 share_all=False)

    # ------------------
    # Av image
    # ------------------
    for i in xrange(ngrids):
        # create axes
        ax = axesgrid[i]
        # show the image
        X, Y = np.meshgrid(np.arange(av_image.shape[1]),
                           np.arange(av_image.shape[0]))

        im = ax.contour(X, Y, av_image,
                origin='lower',
                levels=contours,
                cmap=myplt.truncate_colormap(plt.cm.binary, minval=0.3,)
                #vmin=vlimits[0],
                #vmax=vlimits[1],
                #norm=matplotlib.colors.LogNorm()
                )

        # Asthetics
        ax.set_display_coord_system("fk5")
        ax.set_ticklabel_type("hms", "dms")

        ax.set_xlabel('Right Ascension [J2000]',)
        ax.set_ylabel('Declination [J2000]',)

        ax.locator_params(nbins=4)

        # plot limits
        if limits is not None:
            limits_pix = myplt.convert_wcs_limits(limits, header)
            ax.set_xlim(limits_pix[0],limits_pix[1])
            ax.set_ylim(limits_pix[2],limits_pix[3])

        # Plot cores for each cloud
        # -------------------------
        from matplotlib.patches import Circle
        from matplotlib.collections import PatchCollection

        parameter = parameters[i]
        patches = get_patches(df, header)
        cmap = myplt.truncate_colormap(plt.cm.copper, minval=0.1, maxval=1.0)
        collection = PatchCollection(patches,
                                     cmap=cmap,
                                     edgecolors='k',
                                     linewidth=0.75,
                                     zorder=1000,
                                     )

        # set values in collection
        collection_values = []
        if parameter in ['fraction_diffuse',]:
            collection.set_array(df[parameter])
        else:
            for core in df['core']:
                collection_values.append(core_dict[core][parameter])

            collection.set_array(np.array(collection_values))

        ax.add_collection(collection,
                          )

        # colorbar
        #cbar = axesgrid.cbar_axes[i].colorbar(collection)
        cbar = ax.cax.colorbar(collection)
        if parameter == 'fraction_diffuse':
            cbar.set_label_text(r'Fraction of Diffuse LOS',)

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight', dpi=600)
def plot_h2_sd(plot_dict, contour_image=None, limits=None,
        filename=None, show=True, vlimits=None, av_vlimits=None,
        cloud_names=('california', 'perseus', 'taurus'),):

    # Import external modules
    import matplotlib.pyplot as plt
    import matplotlib
    import numpy as np
    import pyfits as fits
    import matplotlib.pyplot as plt
    import myplotting as myplt
    import pywcsgrid2
    import pywcs
    from pylab import cm # colormaps
    from matplotlib.patches import Polygon
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid

    # Set up plot aesthetics
    plt.clf(); plt.close()

    cmap = plt.cm.copper
    norm = matplotlib.colors.LogNorm()


    # Create figure instance
    fig = plt.figure(figsize=(3.6, 9))

    if 1:
        nrows = 3
        ncols = 1
        nrows_ncols=(3, 1)
        ngrids=3
        figsize = (3.6, 8)
        fig = pywcsgrid2.plt.figure(figsize=figsize)
    else:
        nrows_ncols=(1,1)
        ngrids=1

        axes = AxesGrid(fig, (1,1,1),
                     nrows_ncols=nrows_ncols,
                     ngrids=ngrids,
                     cbar_mode="each",
                     cbar_location='right',
                     cbar_pad="2%",
                     cbar_size='3%',
                     axes_pad=0.1,
                     axes_class=(wcs.Axes,
                                 dict(header=plot_dict['header'])),
                     aspect=True,
                     label_mode='L',
                     share_all=True)

    colorbar_axes = [0.05, 0.97, 0.95, 0.02,]
    map_axes = np.array([0.05, 0.69, 0.95, 0.25])

    for i, cloud_name in enumerate(cloud_names):
        header = plot_dict[cloud_name]['header']
        limits = plot_dict[cloud_name]['limits']
        contour_image = plot_dict[cloud_name]['contour_image']
        contours = plot_dict[cloud_name]['contours']

        #ax = pywcsgrid2.subplot(311+i, header=header)
        ax = pywcsgrid2.axes(map_axes, header=header)

        #ax = fig.add_subplot(311 + i, header=)

        h2_sd = plot_dict[cloud_name]['h2_sd']
        # create axes

        # show the image
        im = ax.imshow(h2_sd,
                interpolation='nearest',
                origin='lower',
                cmap=cmap,
                vmin=vlimits[0],
                vmax=vlimits[1],
                #norm=matplotlib.colors.LogNorm()
                )

        # Asthetics
        ax.set_display_coord_system("fk5")
        ax.set_ticklabel_type("hms", "dms")

        if i == 2:
            ax.set_xlabel('Right Ascension [J2000]',)
        else:
            ax.set_xlabel('')
        ax.set_xlabel('Right Ascension [J2000]',)

        ax.set_ylabel('Declination [J2000]',)

        ax.locator_params(nbins=6)

        #cb_axes.colorbar(im)
        #cb_axes.axis["right"].toggle(ticklabels=False)

        # colorbar
        #cb = ax.cax.colorbar(im)
        cmap.set_bad(color='w')

        # plot limits
        if limits is not None:
            limits_pix = myplt.convert_wcs_limits(limits, header, frame='fk5')
            ax.set_xlim(limits_pix[0],limits_pix[1])
            ax.set_ylim(limits_pix[2],limits_pix[3])

        # Plot Av contours
        if contour_image is not None:
            ax.contour(contour_image, levels=contours, colors='w')

        # Write label to colorbar
        #cb.set_label_text(r'$\Sigma_{\rm H_2} [M_\odot$\,pc$^{-2}$]',)

        if 0:
            if regions is not None:
                for region in props['region_name_pos']:
                    vertices = np.copy(regions[region]['poly_verts']['pixel'])
                    rect = ax.add_patch(Polygon(
                            vertices[:, ::-1],
                            facecolor='none',
                            edgecolor='w'))

        ax.annotate(cloud_name.capitalize(),
                    xytext=(0.96, 0.94),
                    xy=(0.96, 0.94),
                    textcoords='axes fraction',
                    xycoords='axes fraction',
                    size=10,
                    color='k',
                    bbox=dict(boxstyle='square',
                              facecolor='w',
                              alpha=1),
                    horizontalalignment='right',
                    verticalalignment='top',
                    )

        # create new box for plot
        map_axes[1] -= 0.3
        #map_axes[3] -= 0.3

    ax = plt.axes(colorbar_axes,
                  )
    cb = plt.colorbar(im,
                      cax=ax,
                      orientation='horizontal',
                      )
    cb.ax.set_xlabel(r'$\Sigma_{\rm H_2} [{\rm M_\odot}$\,pc$^{-2}$]',)
    cb.ax.xaxis.set_label_position('top')

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight')
    if show:
        fig.show()
示例#9
0
def plot_cores_map(header=None,
                   av_image=None,
                   core_sample=None,
                   limits=None,
                   filename=None,
                   vlimits=(None, None),
                   region_dict=None,
                   plot_regions=True,
                   plot_names=True):

    # Import external modules
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import AxesGrid
    import pywcsgrid2 as wcs
    from matplotlib.patches import Polygon
    import matplotlib.patheffects as PathEffects
    import myplotting as myplt

    # Set up plot aesthetics
    # ----------------------
    plt.close
    plt.clf()

    # Color map
    cmap = plt.cm.gnuplot
    cmap = plt.cm.copper

    # Color cycle, grabs colors from cmap
    color_cycle = [cmap(i) for i in np.linspace(0, 0.8, 2)]
    font_scale = 9

    # Create figure instance
    fig = plt.figure(figsize=(7.5, 5))

    nrows_ncols = (1, 1)
    ngrids = 1

    axesgrid = AxesGrid(fig, (1, 1, 1),
                        nrows_ncols=nrows_ncols,
                        ngrids=ngrids,
                        cbar_mode="each",
                        cbar_location='right',
                        cbar_pad="2%",
                        cbar_size='3%',
                        axes_pad=0.1,
                        axes_class=(wcs.Axes, dict(header=header)),
                        aspect=True,
                        label_mode='L',
                        share_all=True)

    # ------------------
    # Av image
    # ------------------
    # create axes
    ax = axesgrid[0]
    # show the image
    im = ax.imshow(
        av_image,
        interpolation='nearest',
        origin='lower',
        cmap=cmap,
        vmin=vlimits[0],
        vmax=vlimits[1],
        #norm=matplotlib.colors.LogNorm()
    )

    # Asthetics
    ax.set_display_coord_system("gal")
    #ax.set_ticklabel_type("hms", "dms")
    ax.set_ticklabel_type("dms", "dms")

    #ax.set_xlabel('Right Ascension [J2000]',)
    #ax.set_ylabel('Declination [J2000]',)
    ax.set_xlabel('Galactic Longitude [deg]', )
    ax.set_ylabel('Galactic Latitude [deg]', )
    ax.axis["top", ].toggle(ticklabels=True)
    ax.grid(color='w', linewidth=0.5)
    ax.axis[:].major_ticks.set_color("w")

    ax.locator_params(nbins=6)

    # colorbar
    cb = ax.cax.colorbar(im)
    cmap.set_bad(color='w')
    cb.set_label_text(r'$A_V$ [mag]', )

    # plot limits
    if limits is not None:
        limits = myplt.convert_wcs_limits(limits, header, frame='fk5')
        ax.set_xlim(limits[0], limits[1])
        ax.set_ylim(limits[2], limits[3])

    # Plot cores for each cloud
    # -------------------------
    if plot_regions:
        plot_core_regions(ax, region_dict, core_sample)
    else:
        plot_core_locs(ax, region_dict, core_sample, plot_names=plot_names)

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight', dpi=300)
示例#10
0
def plot_nhi_image(nhi_image=None,
                   header=None,
                   contour_image=None,
                   av_image=None,
                   cores=None,
                   props=None,
                   regions=None,
                   title=None,
                   limits=None,
                   contours=None,
                   boxes=False,
                   filename=None,
                   show=True,
                   hi_vlimits=[None, None],
                   av_vlimits=[None, None],
                   cb_text='N(HI)'):

    # Import external modules
    import matplotlib.pyplot as plt
    import matplotlib
    import numpy as np
    import pyfits as fits
    import matplotlib.pyplot as plt
    import myplotting as myplt
    import pywcsgrid2 as wcs
    import pywcs
    from pylab import cm  # colormaps
    from matplotlib.patches import Polygon
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid

    # Set up plot aesthetics
    plt.clf()
    plt.close()

    # Color map
    cmap = plt.cm.gnuplot
    #cmap = myplt.reverse_colormap(plt.cm.copper)
    cmap = plt.cm.copper

    # Create figure instance
    fig = plt.figure(figsize=(7.5, 3.6 * 2))

    if av_image is not None:
        nrows_ncols = (2, 1)
        ngrids = 2
    else:
        nrows_ncols = (1, 1)
        ngrids = 1

    axes = AxesGrid(fig, (1, 1, 1),
                    nrows_ncols=nrows_ncols,
                    ngrids=ngrids,
                    cbar_mode="each",
                    cbar_location='right',
                    cbar_pad="2%",
                    cbar_size='3%',
                    axes_pad=0.1,
                    axes_class=(wcs.Axes, dict(header=header)),
                    aspect=True,
                    label_mode='L',
                    share_all=True)

    # ------------------
    # NHI image
    # ------------------
    # create axes
    ax = axes[0]

    # plot limits
    if limits is not None:
        limits_pix = myplt.convert_wcs_limits(limits, header, frame='fk5')
        limits_pix = np.array(limits_pix, dtype=int)
        ax.set_xlim(limits_pix[0], limits_pix[1])
        ax.set_ylim(limits_pix[2], limits_pix[3])

        # set pixels outside of limits to be nan for correct Vscaling
        nhi_image[:limits_pix[2]] = np.nan
        nhi_image[limits_pix[3]:] = np.nan
        nhi_image[:, :limits_pix[0]] = np.nan
        nhi_image[:, limits_pix[1]:] = np.nan

    # show the image
    im = ax.imshow(
        nhi_image,
        interpolation='nearest',
        origin='lower',
        cmap=cmap,
        vmin=hi_vlimits[0],
        vmax=hi_vlimits[1],
        #norm=matplotlib.colors.LogNorm()
    )

    # Asthetics
    ax.set_display_coord_system("fk5")
    ax.set_ticklabel_type("hms", "dms")

    ax.set_xlabel('Right Ascension [J2000]', )
    ax.set_ylabel('Declination [J2000]', )

    ax.locator_params(nbins=6)

    # colorbar
    cb = ax.cax.colorbar(im)
    cmap.set_bad(color='w')

    # Plot Av contours
    if contour_image is not None:
        ax.contour(contour_image, levels=contours, colors='r')

    # Write label to colorbar
    #cb.set_label_text(r'$N$(H\textsc{i}) [10$^{20}$ cm$^{-2}$]',)
    if cb_text == 'N(HI)':
        cb.set_label_text(r'$N$(H\textsc{i}) [10$^{20}$ cm$^{-2}$]', )
    else:
        cb.set_label_text(cb_text, )

    # Convert sky to pix coordinates
    #wcs_header = pywcs.WCS(header)
    if type(cores) is dict:
        for core in cores:
            pix_coords = cores[core]['center_pixel']

            anno_color = (0.3, 0.5, 1)

            ax.scatter(pix_coords[0],
                       pix_coords[1],
                       color=anno_color,
                       s=200,
                       marker='+',
                       linewidths=2)

            ax.annotate(core,
                        xy=[pix_coords[0], pix_coords[1]],
                        xytext=(5, 5),
                        textcoords='offset points',
                        color=anno_color)

            if boxes:
                rect = ax.add_patch(
                    Polygon(cores[core]['box_vertices'][:, ::-1],
                            facecolor='none',
                            edgecolor=anno_color))

    if regions is not None:
        for region in props['region_name_pos']:
            vertices = np.copy(regions[region]['poly_verts']['pixel'])
            rect = ax.add_patch(
                Polygon(vertices[:, ::-1], facecolor='none', edgecolor='w'))

    # ------------------
    # Av image
    # ------------------
    if av_image is not None:
        # create axes
        ax = axes[1]
        # show the image
        im = ax.imshow(
            av_image,
            interpolation='nearest',
            origin='lower',
            cmap=cmap,
            vmin=av_vlimits[0],
            vmax=av_vlimits[1],
            #norm=matplotlib.colors.LogNorm()
        )

        # Asthetics
        ax.set_display_coord_system("fk5")
        ax.set_ticklabel_type("hms", "dms")

        ax.set_xlabel('Right Ascension [J2000]', )
        ax.set_ylabel('Declination [J2000]', )

        ax.locator_params(nbins=6)

        # colorbar
        cb = ax.cax.colorbar(im)
        cmap.set_bad(color='w')

        # plot limits
        if limits is not None:
            limits_pix = myplt.convert_wcs_limits(limits, header, frame='fk5')
            ax.set_xlim(limits_pix[0], limits_pix[1])
            ax.set_ylim(limits_pix[2], limits_pix[3])

        ax.tick_params(axis='xy', which='major', colors='w')

        # Plot Av contours
        if contour_image is not None:
            ax.contour(contour_image, levels=contours, colors='r')

        # Write label to colorbar
        cb.set_label_text(r'$A_V$ [mag]', )

        # Convert sky to pix coordinates
        #wcs_header = pywcs.WCS(header)
        if type(cores) is dict:
            for core in cores:
                pix_coords = cores[core]['center_pixel']

                anno_color = (0.3, 0.5, 1)

                if boxes:
                    rect = ax.add_patch(
                        Polygon(cores[core]['box_vertices'][:, ::-1],
                                facecolor='none',
                                edgecolor='w'))

        if regions is not None:
            for region in props['region_name_pos']:
                vertices = np.copy(regions[region]['poly_verts']['pixel'])
                rect = ax.add_patch(
                    Polygon(vertices[:, ::-1], facecolor='none',
                            edgecolor='w'))

            if props is not None:
                for region in props['region_name_pos']:
                    if region == 'taurus1':
                        region = 'taurus 1'
                    if region == 'taurus2':
                        region = 'taurus 2'
                    ax.annotate(region.capitalize(),
                                xy=props['region_name_pos'][region]['pixel'],
                                xytext=(0, 0),
                                textcoords='offset points',
                                color='w',
                                fontsize=10,
                                zorder=10)

    if title is not None:
        fig.suptitle(title, fontsize=font_scale)
    if filename is not None:
        plt.savefig(filename, bbox_inches='tight')
    if show:
        fig.show()
def plot_hi_h2_sd(plot_dict, contour_image=None, limits=None, filename=None,
        show=True, hi_vlimits=None, h2_vlimits=None, av_vlimits=None,
        cloud_names=('california', 'perseus', 'taurus'), hi_contours=None,
        h2_contours=None,):

    # Import external modules
    import matplotlib.pyplot as plt
    import matplotlib
    import numpy as np
    import pyfits as fits
    import matplotlib.pyplot as plt
    import myplotting as myplt
    import pywcsgrid2
    import pywcs
    from pylab import cm # colormaps
    from matplotlib.patches import Polygon
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid

    # Set up plot aesthetics
    plt.clf(); plt.close()

    # Colormap settings
    cmap = plt.cm.copper
    cmap.set_bad(color='w')
    norm = matplotlib.colors.LogNorm()

    # Create figure instance
    figsize = (7.5, 9)
    fig = pywcsgrid2.plt.figure(figsize=figsize)

    colorbar_axes = [0.05, 0.97, 0.95, 0.02,]
    map_axes = np.array([0.05, 0.69, 0.95, 0.25])
    map_axes = np.array([0.05, 0.31, 0.95, 0.25])

    # plot HI and H2 maps for each cloud
    # ---------------------------------------------------------------------------
    for i, cloud_name in enumerate(cloud_names):
        # get image properties
        # -----------------------------------------------------------------------
        header = plot_dict[cloud_name]['header']
        limits = plot_dict[cloud_name]['limits']
        contour_image = plot_dict[cloud_name]['contour_image']
        contours = plot_dict[cloud_name]['contours']

        # Prep axes instance
        # -----------------------------------------------------------------------
        nrows_ncols=(1, 2)
        ngrids=2

        # only show cbar for first row
        if i == 0:
            cbar_mode = "each"
        else:
            cbar_mode = None

        axes = AxesGrid(fig, 311 + i, #(3,1,i),
                     nrows_ncols=nrows_ncols,
                     ngrids=ngrids,
                     cbar_mode=cbar_mode,
                     cbar_location='top',
                     cbar_pad="5%",
                     cbar_size='10%',
                     axes_pad=0.1,
                     axes_class=(pywcsgrid2.Axes,
                                 dict(header=header)),
                     aspect=True,
                     label_mode='L',
                     share_all=True,
                     )

        # get axes from row
        ax1 = axes[0]
        ax2 = axes[1]

        # Plot the maps
        # -----------------------------------------------------------------------
        # HI surface density map
        hi_sd = plot_dict[cloud_name]['hi_sd']

        # H2 surface density map
        h2_sd = plot_dict[cloud_name]['h2_sd']

        # show the images
        im_hi = ax1.imshow(hi_sd,
                interpolation='nearest',
                origin='lower',
                cmap=cmap,
                vmin=hi_vlimits[0],
                vmax=hi_vlimits[1],
                #norm=matplotlib.colors.LogNorm()
                )
        im_h2 = ax2.imshow(h2_sd,
                interpolation='nearest',
                origin='lower',
                cmap=cmap,
                vmin=h2_vlimits[0],
                vmax=h2_vlimits[1],
                #norm=matplotlib.colors.LogNorm()
                )

        # Asthetics
        # -----------------------------------------------------------------------
        for ax in (ax1, ax2):
            ax.set_display_coord_system("fk5")
            ax.set_ticklabel_type("hms", "dms")
            ax.set_xlabel('Right Ascension [J2000]',)
            ax.set_ylabel('Declination [J2000]',)
            ax.locator_params(nbins=5)

        # colorbar
        # -----------------------------------------------------------------------
        cb_hi = ax1.cax.colorbar(im_hi)
        cb_h2 = ax2.cax.colorbar(im_h2)

        # Write label to colorbar
        cb_hi.set_label_text(r'$\Sigma_{\rm HI}$ [M$_\odot$\,pc$^{-2}$]',)
        cb_h2.set_label_text(r'$\Sigma_{\rm H_2}$ [M$_\odot$\,pc$^{-2}$]',)

        # plot limits
        # -----------------------------------------------------------------------
        if limits is not None:
            limits_pix = myplt.convert_wcs_limits(limits, header, frame='fk5')
            ax1.set_xlim(limits_pix[0],limits_pix[1])
            ax1.set_ylim(limits_pix[2],limits_pix[3])
            ax2.set_xlim(limits_pix[0],limits_pix[1])
            ax2.set_ylim(limits_pix[2],limits_pix[3])

        # Plot contours
        # -----------------------------------------------------------------------
        if hi_contours is not None:
            hi_colors = myplt.get_color_cycle(num_colors=len(hi_contours),
                                              cmap=plt.cm.binary,
                                              )
            ax1.contour(hi_sd, levels=hi_contours, colors=hi_colors)
        if h2_contours is not None:
            h2_colors = myplt.get_color_cycle(num_colors=len(h2_contours),
                                              cmap=plt.cm.binary,
                                              )
            ax2.contour(h2_sd, levels=h2_contours, colors=h2_colors)

        # Cloud names
        # -----------------------------------------------------------------------
        ax1.annotate(cloud_name.capitalize(),
                    xytext=(0.96, 0.94),
                    xy=(0.96, 0.94),
                    textcoords='axes fraction',
                    xycoords='axes fraction',
                    size=10,
                    color='k',
                    bbox=dict(boxstyle='square',
                              facecolor='w',
                              alpha=1),
                    horizontalalignment='right',
                    verticalalignment='top',
                    )

        # create new box for plot
        # -----------------------------------------------------------------------
        #map_axes[1] -= 0.3
        map_axes[1] += 0.3

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight')
    if show:
        fig.show()
def plot_av_image(header=None, contour_image=None,
        av_image=None, cores=None, props=None, regions=None, title=None,
        limits=None, contours=None, boxes=False, filename=None,
        limits_type='wcs',
        show=True, av_vlimits=None,):

    # Import external modules
    import matplotlib.pyplot as plt
    import matplotlib
    import numpy as np
    import pyfits as fits
    import matplotlib.pyplot as plt
    import myplotting as myplt
    import pywcsgrid2 as wcs
    import pywcs
    from pylab import cm # colormaps
    from matplotlib.patches import Polygon
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid

    # Set up plot aesthetics
    plt.clf(); plt.close()

    # Color map
    cmap = plt.cm.gnuplot
    #cmap = myplt.reverse_colormap(plt.cm.copper)
    cmap = plt.cm.copper

    # Create figure instance
    fig = plt.figure(figsize=(7.5, 3.6))

    nrows_ncols=(1,1)
    ngrids=1

    axes = AxesGrid(fig, (1,1,1),
                 nrows_ncols=nrows_ncols,
                 ngrids=ngrids,
                 cbar_mode="each",
                 cbar_location='right',
                 cbar_pad="2%",
                 cbar_size='3%',
                 axes_pad=0.1,
                 axes_class=(wcs.Axes,
                             dict(header=header)),
                 aspect=True,
                 label_mode='L',
                 share_all=True)

    # ------------------
    # Av image
    # ------------------
    # create axes
    ax = axes[0]
    # show the image
    im = ax.imshow(av_image,
            interpolation='nearest',origin='lower',
            cmap=cmap,
            vmin=av_vlimits[0],
            vmax=av_vlimits[1],
            #norm=matplotlib.colors.LogNorm()
            )

    # Asthetics
    ax.set_display_coord_system("fk5")
    ax.set_ticklabel_type("hms", "dms")

    ax.set_xlabel('Right Ascension [J2000]',)
    ax.set_ylabel('Declination [J2000]',)
    ax.axis[:].major_ticks.set_color("w")

    ax.locator_params(nbins=6)

    # colorbar
    cb = ax.cax.colorbar(im)
    cmap.set_bad(color='w')

    # plot limits
    if limits is not None:
        if limits_type == 'wcs':
            print limits
            limits_pix = myplt.convert_wcs_limits(limits, header, frame='fk5')
        else:
            limits_pix = limits
        ax.set_xlim(limits_pix[0],limits_pix[1])
        ax.set_ylim(limits_pix[2],limits_pix[3])

    ax.tick_params(axis='xy', which='major', colors='w')

    # Plot Av contours
    if contour_image is not None:
        ax.contour(contour_image, levels=contours, colors='r')

    # Write label to colorbar
    cb.set_label_text(r'$A_V$ [mag]',)

    # Convert sky to pix coordinates
    #wcs_header = pywcs.WCS(header)
    if type(cores) is dict:
        for core in cores:
            pix_coords = cores[core]['center_pixel']

            anno_color = (0.3, 0.5, 1)

            if boxes:
                rect = ax.add_patch(Polygon(
                    cores[core]['box_vertices'][:, ::-1],
                        facecolor='none',
                        edgecolor='w'))

    if regions is not None:
        for region in props['region_name_pos']:
            vertices = np.copy(regions[region]['poly_verts']['pixel'])
            rect = ax.add_patch(Polygon(
                    vertices[:, ::-1],
                    facecolor='none',
                    edgecolor='w'))

        if props is not None:
            for region in props['region_name_pos']:
                if region == 'taurus1':
                    region = 'taurus 1'
                if region == 'taurus2':
                    region = 'taurus 2'
                ax.annotate(region.capitalize(),
                            xy=props['region_name_pos'][region]['pixel'],
                            xytext=(0,0),
                            textcoords='offset points',
                            color='w',
                            fontsize=10,
                            zorder=10)

    if title is not None:
        fig.suptitle(title, fontsize=font_scale)
    if filename is not None:
        plt.savefig(filename, bbox_inches='tight')
    if show:
        fig.show()
def plot_hi_h2_sd(
    plot_dict,
    contour_image=None,
    limits=None,
    filename=None,
    show=True,
    hi_vlimits=None,
    h2_vlimits=None,
    av_vlimits=None,
    cloud_names=('california', 'perseus', 'taurus'),
    hi_contours=None,
    h2_contours=None,
):

    # Import external modules
    import matplotlib.pyplot as plt
    import matplotlib
    import numpy as np
    import pyfits as fits
    import matplotlib.pyplot as plt
    import myplotting as myplt
    import pywcsgrid2
    import pywcs
    from pylab import cm  # colormaps
    from matplotlib.patches import Polygon
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid

    # Set up plot aesthetics
    plt.clf()
    plt.close()

    # Colormap settings
    cmap = plt.cm.copper
    cmap.set_bad(color='w')
    norm = matplotlib.colors.LogNorm()

    # Create figure instance
    figsize = (7.5, 9)
    fig = pywcsgrid2.plt.figure(figsize=figsize)

    colorbar_axes = [
        0.05,
        0.97,
        0.95,
        0.02,
    ]
    map_axes = np.array([0.05, 0.69, 0.95, 0.25])
    map_axes = np.array([0.05, 0.31, 0.95, 0.25])

    # plot HI and H2 maps for each cloud
    # ---------------------------------------------------------------------------
    for i, cloud_name in enumerate(cloud_names):
        # get image properties
        # -----------------------------------------------------------------------
        header = plot_dict[cloud_name]['header']
        limits = plot_dict[cloud_name]['limits']
        contour_image = plot_dict[cloud_name]['contour_image']
        contours = plot_dict[cloud_name]['contours']

        # Prep axes instance
        # -----------------------------------------------------------------------
        nrows_ncols = (1, 2)
        ngrids = 2

        # only show cbar for first row
        if i == 0:
            cbar_mode = "each"
        else:
            cbar_mode = None

        axes = AxesGrid(
            fig,
            311 + i,  #(3,1,i),
            nrows_ncols=nrows_ncols,
            ngrids=ngrids,
            cbar_mode=cbar_mode,
            cbar_location='top',
            cbar_pad="5%",
            cbar_size='10%',
            axes_pad=0.1,
            axes_class=(pywcsgrid2.Axes, dict(header=header)),
            aspect=True,
            label_mode='L',
            share_all=True,
        )

        # get axes from row
        ax1 = axes[0]
        ax2 = axes[1]

        # Plot the maps
        # -----------------------------------------------------------------------
        # HI surface density map
        hi_sd = plot_dict[cloud_name]['hi_sd']

        # H2 surface density map
        h2_sd = plot_dict[cloud_name]['h2_sd']

        # show the images
        im_hi = ax1.imshow(
            hi_sd,
            interpolation='nearest',
            origin='lower',
            cmap=cmap,
            vmin=hi_vlimits[0],
            vmax=hi_vlimits[1],
            #norm=matplotlib.colors.LogNorm()
        )
        im_h2 = ax2.imshow(
            h2_sd,
            interpolation='nearest',
            origin='lower',
            cmap=cmap,
            vmin=h2_vlimits[0],
            vmax=h2_vlimits[1],
            #norm=matplotlib.colors.LogNorm()
        )

        # Asthetics
        # -----------------------------------------------------------------------
        for ax in (ax1, ax2):
            ax.set_display_coord_system("fk5")
            ax.set_ticklabel_type("hms", "dms")
            ax.set_xlabel('Right Ascension [J2000]', )
            ax.set_ylabel('Declination [J2000]', )
            ax.locator_params(nbins=5)

        # colorbar
        # -----------------------------------------------------------------------
        cb_hi = ax1.cax.colorbar(im_hi)
        cb_h2 = ax2.cax.colorbar(im_h2)

        # Write label to colorbar
        cb_hi.set_label_text(r'$\Sigma_{\rm HI}$ [M$_\odot$\,pc$^{-2}$]', )
        cb_h2.set_label_text(r'$\Sigma_{\rm H_2}$ [M$_\odot$\,pc$^{-2}$]', )

        # plot limits
        # -----------------------------------------------------------------------
        if limits is not None:
            limits_pix = myplt.convert_wcs_limits(limits, header, frame='fk5')
            ax1.set_xlim(limits_pix[0], limits_pix[1])
            ax1.set_ylim(limits_pix[2], limits_pix[3])
            ax2.set_xlim(limits_pix[0], limits_pix[1])
            ax2.set_ylim(limits_pix[2], limits_pix[3])

        # Plot contours
        # -----------------------------------------------------------------------
        if hi_contours is not None:
            hi_colors = myplt.get_color_cycle(
                num_colors=len(hi_contours),
                cmap=plt.cm.binary,
            )
            ax1.contour(hi_sd, levels=hi_contours, colors=hi_colors)
        if h2_contours is not None:
            h2_colors = myplt.get_color_cycle(
                num_colors=len(h2_contours),
                cmap=plt.cm.binary,
            )
            ax2.contour(h2_sd, levels=h2_contours, colors=h2_colors)

        # Cloud names
        # -----------------------------------------------------------------------
        ax1.annotate(
            cloud_name.capitalize(),
            xytext=(0.96, 0.94),
            xy=(0.96, 0.94),
            textcoords='axes fraction',
            xycoords='axes fraction',
            size=10,
            color='k',
            bbox=dict(boxstyle='square', facecolor='w', alpha=1),
            horizontalalignment='right',
            verticalalignment='top',
        )

        # create new box for plot
        # -----------------------------------------------------------------------
        #map_axes[1] -= 0.3
        map_axes[1] += 0.3

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight')
    if show:
        fig.show()
def plot_h2_sd(
        plot_dict,
        contour_image=None,
        limits=None,
        filename=None,
        show=True,
        vlimits=None,
        av_vlimits=None,
        cloud_names=('california', 'perseus', 'taurus'),
):

    # Import external modules
    import matplotlib.pyplot as plt
    import matplotlib
    import numpy as np
    import pyfits as fits
    import matplotlib.pyplot as plt
    import myplotting as myplt
    import pywcsgrid2
    import pywcs
    from pylab import cm  # colormaps
    from matplotlib.patches import Polygon
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid

    # Set up plot aesthetics
    plt.clf()
    plt.close()

    cmap = plt.cm.copper
    norm = matplotlib.colors.LogNorm()

    # Create figure instance
    fig = plt.figure(figsize=(3.6, 9))

    if 1:
        nrows = 3
        ncols = 1
        nrows_ncols = (3, 1)
        ngrids = 3
        figsize = (3.6, 8)
        fig = pywcsgrid2.plt.figure(figsize=figsize)
    else:
        nrows_ncols = (1, 1)
        ngrids = 1

        axes = AxesGrid(fig, (1, 1, 1),
                        nrows_ncols=nrows_ncols,
                        ngrids=ngrids,
                        cbar_mode="each",
                        cbar_location='right',
                        cbar_pad="2%",
                        cbar_size='3%',
                        axes_pad=0.1,
                        axes_class=(wcs.Axes,
                                    dict(header=plot_dict['header'])),
                        aspect=True,
                        label_mode='L',
                        share_all=True)

    colorbar_axes = [
        0.05,
        0.97,
        0.95,
        0.02,
    ]
    map_axes = np.array([0.05, 0.69, 0.95, 0.25])

    for i, cloud_name in enumerate(cloud_names):
        header = plot_dict[cloud_name]['header']
        limits = plot_dict[cloud_name]['limits']
        contour_image = plot_dict[cloud_name]['contour_image']
        contours = plot_dict[cloud_name]['contours']

        #ax = pywcsgrid2.subplot(311+i, header=header)
        ax = pywcsgrid2.axes(map_axes, header=header)

        #ax = fig.add_subplot(311 + i, header=)

        h2_sd = plot_dict[cloud_name]['h2_sd']
        # create axes

        # show the image
        im = ax.imshow(
            h2_sd,
            interpolation='nearest',
            origin='lower',
            cmap=cmap,
            vmin=vlimits[0],
            vmax=vlimits[1],
            #norm=matplotlib.colors.LogNorm()
        )

        # Asthetics
        ax.set_display_coord_system("fk5")
        ax.set_ticklabel_type("hms", "dms")

        if i == 2:
            ax.set_xlabel('Right Ascension [J2000]', )
        else:
            ax.set_xlabel('')
        ax.set_xlabel('Right Ascension [J2000]', )

        ax.set_ylabel('Declination [J2000]', )

        ax.locator_params(nbins=6)

        #cb_axes.colorbar(im)
        #cb_axes.axis["right"].toggle(ticklabels=False)

        # colorbar
        #cb = ax.cax.colorbar(im)
        cmap.set_bad(color='w')

        # plot limits
        if limits is not None:
            limits_pix = myplt.convert_wcs_limits(limits, header, frame='fk5')
            ax.set_xlim(limits_pix[0], limits_pix[1])
            ax.set_ylim(limits_pix[2], limits_pix[3])

        # Plot Av contours
        if contour_image is not None:
            ax.contour(contour_image, levels=contours, colors='w')

        # Write label to colorbar
        #cb.set_label_text(r'$\Sigma_{\rm H_2} [M_\odot$\,pc$^{-2}$]',)

        if 0:
            if regions is not None:
                for region in props['region_name_pos']:
                    vertices = np.copy(regions[region]['poly_verts']['pixel'])
                    rect = ax.add_patch(
                        Polygon(vertices[:, ::-1],
                                facecolor='none',
                                edgecolor='w'))

        ax.annotate(
            cloud_name.capitalize(),
            xytext=(0.96, 0.94),
            xy=(0.96, 0.94),
            textcoords='axes fraction',
            xycoords='axes fraction',
            size=10,
            color='k',
            bbox=dict(boxstyle='square', facecolor='w', alpha=1),
            horizontalalignment='right',
            verticalalignment='top',
        )

        # create new box for plot
        map_axes[1] -= 0.3
        #map_axes[3] -= 0.3

    ax = plt.axes(colorbar_axes, )
    cb = plt.colorbar(
        im,
        cax=ax,
        orientation='horizontal',
    )
    cb.ax.set_xlabel(r'$\Sigma_{\rm H_2} [{\rm M_\odot}$\,pc$^{-2}$]', )
    cb.ax.xaxis.set_label_position('top')

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight')
    if show:
        fig.show()
def plot_cores_map(header=None, av_image=None, core_sample=None, limits=None,
        filename=None, vlimits=(None,None), region_dict=None,
        plot_regions=True, plot_names=True):

    # Import external modules
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import AxesGrid
    import pywcsgrid2 as wcs
    from matplotlib.patches import Polygon
    import matplotlib.patheffects as PathEffects
    import myplotting as myplt

    # Set up plot aesthetics
    # ----------------------
    plt.close;plt.clf()

    # Color map
    cmap = plt.cm.gnuplot
    cmap = plt.cm.copper

    # Color cycle, grabs colors from cmap
    color_cycle = [cmap(i) for i in np.linspace(0, 0.8, 2)]
    font_scale = 9

    # Create figure instance
    fig = plt.figure(figsize=(7.5, 5))

    nrows_ncols=(1,1)
    ngrids=1

    axesgrid = AxesGrid(fig, (1,1,1),
                 nrows_ncols=nrows_ncols,
                 ngrids=ngrids,
                 cbar_mode="each",
                 cbar_location='right',
                 cbar_pad="2%",
                 cbar_size='3%',
                 axes_pad=0.1,
                 axes_class=(wcs.Axes,
                             dict(header=header)),
                 aspect=True,
                 label_mode='L',
                 share_all=True)

    # ------------------
    # Av image
    # ------------------
    # create axes
    ax = axesgrid[0]
    # show the image
    im = ax.imshow(av_image,
            interpolation='nearest',
            origin='lower',
            cmap=cmap,
            vmin=vlimits[0],
            vmax=vlimits[1],
            #norm=matplotlib.colors.LogNorm()
            )

    # Asthetics
    ax.set_display_coord_system("gal")
    #ax.set_ticklabel_type("hms", "dms")
    ax.set_ticklabel_type("dms", "dms")

    #ax.set_xlabel('Right Ascension [J2000]',)
    #ax.set_ylabel('Declination [J2000]',)
    ax.set_xlabel('Galactic Longitude [deg]',)
    ax.set_ylabel('Galactic Latitude [deg]',)
    ax.axis["top",].toggle(ticklabels=True)
    ax.grid(color='w', linewidth=0.5)
    ax.axis[:].major_ticks.set_color("w")

    ax.locator_params(nbins=6)

    # colorbar
    cb = ax.cax.colorbar(im)
    cmap.set_bad(color='w')
    cb.set_label_text(r'$A_V$ [mag]',)

    # plot limits
    if limits is not None:
        limits = myplt.convert_wcs_limits(limits, header, frame='fk5')
        ax.set_xlim(limits[0],limits[1])
        ax.set_ylim(limits[2],limits[3])

    # Plot cores for each cloud
    # -------------------------
    if plot_regions:
        plot_core_regions(ax, region_dict, core_sample)
    else:
        plot_core_locs(ax, region_dict, core_sample, plot_names=plot_names)

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight', dpi=300)
示例#16
0
def plot_rad_map(header=None,
                 contour_image=None,
                 rad_field=None,
                 cores=None,
                 cores_to_keep=None,
                 props=None,
                 cloud_dict=None,
                 regions=None,
                 title=None,
                 limits=None,
                 contours=None,
                 boxes=False,
                 savedir='./',
                 filename=None,
                 show=False,
                 hi_vlimits=None,
                 vlimits=None,
                 vscale='linear'):

    # Import external modules
    import matplotlib.pyplot as plt
    import matplotlib
    import numpy as np
    from mpl_toolkits.axes_grid1 import AxesGrid
    import pyfits as pf
    import matplotlib.pyplot as plt
    import pywcsgrid2 as wcs
    import pywcs
    from pylab import cm  # colormaps
    from matplotlib.patches import Polygon
    import matplotlib.patheffects as PathEffects
    import myplotting as myplt

    # Set up plot aesthetics
    # ----------------------
    #plt.close();plt.clf()

    # Color map
    cmap = plt.cm.copper

    # Color cycle, grabs colors from cmap

    # Create figure instance
    fig = plt.figure(figsize=(7.5, 5))

    if rad_field is not None:
        nrows_ncols = (1, 1)
        ngrids = 1

    imagegrid = AxesGrid(fig, (1, 1, 1),
                         nrows_ncols=nrows_ncols,
                         ngrids=ngrids,
                         cbar_mode="single",
                         cbar_location='right',
                         cbar_pad="2%",
                         cbar_size='3%',
                         axes_pad=0.1,
                         axes_class=(wcs.Axes, dict(header=header)),
                         aspect=True,
                         label_mode='L',
                         share_all=True)

    # ------------------
    # Av image
    # ------------------
    # create axes
    ax = imagegrid[0]

    #ax = wcs.subplot(111, header=header)

    if vscale == 'log':
        norm = matplotlib.colors.LogNorm()
    else:
        norm = None

    # show the image
    im = ax.imshow(
        rad_field,
        interpolation='nearest',
        origin='lower',
        cmap=cmap,
        norm=norm,
        vmin=vlimits[0],
        vmax=vlimits[1],
    )

    # Asthetics
    #ax.set_display_coord_system("fk5")
    #ax.set_ticklabel_type("hms", "dms")

    #ax.set_xlabel('Right Ascension [J2000]',)
    #ax.set_ylabel('Declination [J2000]',)

    ax.set_display_coord_system("gal")
    #ax.set_ticklabel_type("hms", "dms")
    ax.set_ticklabel_type("dms", "dms")

    #ax.set_xlabel('Right Ascension [J2000]',)
    #ax.set_ylabel('Declination [J2000]',)
    ax.set_xlabel('Galactic Longitude [deg]', )
    ax.set_ylabel('Galactic Latitude [deg]', )
    ax.axis["top", ].toggle(ticklabels=True)
    ax.grid(color='w', linewidth=0.5)
    ax.axis[:].major_ticks.set_color("w")

    cmap.set_bad(color='w')

    #ax.locator_params(nbins=6)
    ax.locator_params(nbins=6)

    # colorbar
    from matplotlib.ticker import LogFormatter
    formatter = LogFormatter(10, labelOnlyBase=False)
    ticks = np.logspace(
        np.log10(vlimits[0]),
        np.log10(vlimits[1]),
        #np.log10(vlimits[1]) - np.log10(vlimits[0]),
        5,
    )

    from matplotlib.ticker import LogFormatterMathtext

    if 1:
        cb = ax.cax.colorbar(im,
                             #ticks=ticks,
                             #format=LogFormatterMathtext(),
                             )
        #cb.set_label_text(r'log$_{10}$[$U_{0,M83}$]',)
        cb.set_label_text(r'$U\,[U_{\rm D78}$]', )
    else:
        from mpl_toolkits.axes_grid1 import make_axes_locatable
        divider = make_axes_locatable(ax)
        #cax = divider.append_axes("right", size="5%", pad=0.05)

        #plt.colorbar(im, cax=cax)

        #cb = fig.colorbar(im, ax=ax)
        #cb.ax.set_ylabel(r'$U_{0,M83}$',)

    # plot limits
    if limits is not None:
        limits_pix = myplt.convert_wcs_limits(limits, header, frame='fk5')
        ax.set_xlim(limits_pix[0], limits_pix[1])
        ax.set_ylim(limits_pix[2], limits_pix[3])

    # Plot Av contours
    if contour_image is not None:
        ax.contour(contour_image, levels=contours, colors='r')

        if props is not None:
            if 0:
                for region in props['region_name_pos']:
                    if region == 'taurus1':
                        region = 'taurus 1'
                    if region == 'taurus2':
                        region = 'taurus 2'
                    ax.annotate(region.capitalize(),
                                xy=props['region_name_pos'][region]['pixel'],
                                xytext=(0, 0),
                                textcoords='offset points',
                                color='w',
                                fontsize=7,
                                zorder=10)

    if regions is not None:
        for region in props['region_name_pos']:
            vertices = np.copy(regions[region]['poly_verts']['pixel'])
            rect = ax.add_patch(
                Polygon(vertices[:, ::-1], facecolor='none', edgecolor='w'))

# ax.legend(rects, core_labels, bbox_to_anchor=(1.05, 1), loc=2,
#         borderaxespad=0.)
#ax.legend(rects, core_labels, bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
#       ncol=5, mode="expand", borderaxespad=0.)

    if filename is not None:
        plt.savefig(savedir + filename, bbox_inches='tight')
    if show:
        fig.show()