def plot_planck_vs_2mass(
        av_k09,
        av_pl,
        filename=None,
        av_error=None,
        contour_plot=True,
        levels=10,
        plot_median=True,
        limits=None,
        labels=['', ''],
        scale=('linear', 'linear'),
        title='',
        fit_labels=['', ''],
        gridsize=(100, 100),
):

    # import external modules
    import numpy as np
    import math
    import matplotlib.pyplot as plt
    import matplotlib
    from matplotlib import cm
    from astroML.plotting import scatter_contour
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid
    import myplotting as myplt

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

    # color map
    myplt.set_color_cycle(num_colors=3)

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

    axes = AxesGrid(
        fig,
        (1, 1, 1),
        nrows_ncols=(1, 1),
        ngrids=1,
        axes_pad=0.25,
        aspect=False,
        label_mode='L',
        share_all=True,
        #cbar_mode='single',
        cbar_pad=0.1,
        cbar_size=0.2,
    )

    # Drop the NaNs from the images
    if type(av_error) is float or av_error is None:
        indices = np.where((av_pl == av_pl) &\
                           (av_k09 == av_k09)
                           )

    av_pl = av_pl[indices]
    av_k09 = av_k09[indices]

    # Create plot
    ax = axes[0]

    if limits is None:
        xmin = np.min(av_k09)
        ymin = np.min(av_k09)
        xmax = np.max(av_pl)
        ymax = np.max(av_pl)
        xscalar = 0.15 * xmax
        yscalar = 0.15 * ymax
        limits = [
            xmin - xscalar, xmax + xscalar, ymin - yscalar, ymax + yscalar
        ]

    if contour_plot:

        contour_range = ((limits[0], limits[1]), (limits[2], limits[3]))

        cmap = myplt.truncate_colormap(plt.cm.binary, 0.2, 1, 1000)

        l1 = myplt.scatter_contour(
            av_k09,
            av_pl,
            threshold=3,
            log_counts=1,
            levels=levels,
            ax=ax,
            histogram2d_args=dict(bins=30, range=contour_range),
            plot_args=dict(marker='o',
                           linestyle='none',
                           color='black',
                           alpha=0.3,
                           markersize=2),
            contour_args=dict(
                #cmap=plt.cm.binary,
                cmap=cmap,
                #cmap=cmap,
            ),
        )

    else:
        image = ax.errorbar(nhi_nonans.ravel(),
                            av_nonans.ravel(),
                            yerr=(av_error_nonans.ravel()),
                            alpha=0.2,
                            color='k',
                            marker='^',
                            ecolor='k',
                            linestyle='None',
                            markersize=3)

    # Plot sensitivies
    #av_limit = np.median(av_errors[0])
    #ax.axvline(av_limit, color='k', linestyle='--')

    # Plot 1 to 1 pline
    if 1:
        x_fit = np.linspace(-5, 200, 1000)
        p, V = \
                np.polyfit(av_k09, av_pl, deg=1,
                           #w=np.abs(1.0/av_error_nonans.ravel()),
                           cov=True
                           )

        y_poly_fit = p[0] * x_fit + p[1]
    if 1:
        ax.plot(x_fit,
                y_poly_fit,
                color='r',
                linestyle='dashed',
                linewidth=2,
                label=\
                    'Poly fit: \n' + \
                    fit_labels[0] + ' = ' + '{0:.1f}'.format(p[0]) + \
                    r'$\times$ ' + fit_labels[1] + \
                    ' + {0:.1f} mag'.format(p[1]),
                alpha=0.7,
                )
    if 0:
        from scipy.interpolate import UnivariateSpline

        spl = UnivariateSpline(av_k09, av_pl)
        ax.plot(x_fit, spl(x_fit), linewidth=3, alpha=0.5)

    if 0:
        print('Bootstrapping...')
        # bootstrap conf intervals
        import scipy as sp
        bootindex = sp.random.random_integers
        nboot = 20
        x_fit = av_k09
        y_fit = p[0] * x_fit + p[1]
        r = av_pl - y_fit
        for i in xrange(
                nboot):  # loop over n bootstrap samples from the resids
            pc = sp.polyfit(av_k09, y_fit + r[bootindex(0,
                                                        len(r) - 1, len(r))],
                            1)
            ax.plot(x_fit,
                    sp.polyval(pc, x_fit),
                    'k-',
                    linewidth=2,
                    alpha=1.0 / float(nboot))

    # Annotations
    anno_xpos = 0.95

    ax.set_xscale(scale[0], nonposx='clip')
    ax.set_yscale(scale[1], nonposy='clip')

    ax.set_xlim(limits[0], limits[1])
    ax.set_ylim(limits[2], limits[3])

    # Adjust asthetics
    #ax.set_xlabel(r'$A_{V,{\rm K+09}}$ [mag]')
    #ax.set_ylabel(r'$A_{V,{\rm Planck}}$ [mag]')
    ax.set_xlabel(labels[0])
    ax.set_ylabel(labels[1])
    ax.set_title(title)
    ax.legend(loc='best')

    if filename is not None:
        plt.savefig(filename)
import matplotlib.patches as mpatches
from mpl_toolkits.axes_grid1.axes_grid import AxesGrid
from matplotlib.offsetbox import AnchoredText

fig = plt.figure(1, figsize=(8, 5))
fig.clf()


def add_at(ax, t, loc=2):
    fp = dict(size=8)
    _at = AnchoredText(t, loc=loc, prop=fp)
    ax.add_artist(_at)
    return _at


grid = AxesGrid(fig, 111, (3, 5), label_mode="1", share_all=True)

grid[0].set_autoscale_on(False)

x1, y1 = 0.3, 0.3
x2, y2 = 0.7, 0.7


def demo_con_style(ax, connectionstyle, label=None):
    if label is None:
        label = connectionstyle

    x1, y1 = 0.3, 0.2
    x2, y2 = 0.8, 0.6

    ax.plot([x1, x2], [y1, y2], ".")
Exemplo n.º 3
0
def cMapFirTir(tirValues=None,
               firValues=None,
               wcs=None,
               wcsMinMax=None,
               raCenter=None,
               decCenter=None,
               fluxImage=None,
               plotTitle=None,
               saveName=None):
    """
    Make color maps of the TIR and FIR

    Parameters:
    -----------
    tirValues: array_like
        2D array of the total infrared fluxes.
    firValues: array_like
        2D array of the far infrared fluxes.
    wcs: WCS
        The WCS of the object.
    wcsMinMax: array_like
        The limits (colMin,colMax,rowMin,rowMax) of the colormap spaxels.
    fluxImage: array_like
        The continuum fluxes to overplot contours.
    ra/decCenter: float
        RA and Dec of the galaxy's center.
    plotTitle: str
        The title of the plot.
    saveName: str
        The path and/or name of the file to save the colormaps.
    """
    matplotlib.rcParams['xtick.labelsize'] = 6
    matplotlib.rcParams['ytick.labelsize'] = 6
    matplotlib.rcParams['axes.labelsize'] = 6
    fig = plt.figure()

    # Grid helper
    grid_helper = pywcsgrid2.GridHelper(wcs=wcs)
    # Setup the grid for plotting.
    grid = AxesGrid(fig,
                    111,
                    nrows_ncols=(1, 2),
                    axes_pad=(0.45, 0.07),
                    cbar_mode='each',
                    cbar_location='right',
                    cbar_pad=0,
                    axes_class=(pywcsgrid2.Axes,
                                dict(grid_helper=grid_helper)),
                    share_all=True)
    for ii in range(2):
        # Get the axis.
        ax = grid[ii]
        # Set background color
        ax.patch.set_facecolor('black')

        # Create the colormap.
        cmap = matplotlib.cm.rainbow
        cmap.set_bad('black', 1.)  #Set masked pixels to be black.

        # Plot the image.
        if ii == 0:
            image = firValues
            label = r'FIR [W m$^{-2}$]'
        if ii == 1:
            image = tirValues
            label = r'TIR [W m$^{-2}$]'
        #im = ax.contourf(image,cmap=cmap)
        im = ax.imshow(image, cmap=cmap)

        # Label the flux inside the subplot.
        at = AnchoredText(label, loc=2, prop=dict(size=5))
        ax.add_artist(at)
        # Flip the axis per convention.
        ax.invert_yaxis()
        # Mark the center of the galaxy.
        ax['fk5'].plot(raCenter,
                       decCenter,
                       markeredgewidth=.9,
                       marker='+',
                       color='k',
                       ms=7)
        # Mark flux contours and continuum contours.
        ax.contour(fluxImage, linewidths=0.85, alpha=0.8, colors='black')

        # Make the tickmarks black.
        ax.tick_params(axis='both', colors='black', width=0)
        # Make a colorbar for each image.
        cax1 = grid.cbar_axes[ii]
        cbar1 = cax1.colorbar(im, format='%.2e')
        cbar1.ax.tick_params(labelsize=4)
    # Set figure title.
    fig.text(0.5, 0.82, plotTitle, ha='center', fontsize=10)
    # Save the plot to PDF
    pp = PdfPages(saveName)
    pp.savefig(fig, bbox_inches='tight')
    pp.close()
    plt.close()
Exemplo n.º 4
0
def cMapPdrParams4Fluxes(pdrParams=None,
                         wcs=None,
                         wcsMinMax=None,
                         raCenter=None,
                         decCenter=None,
                         objectName=None,
                         plotTitle=None,
                         saveFileName=None,
                         cmapMinMax=None):
    """
    Plot the PDR parameters which have been "corrected" to
    more believable values.

    Parameters:
    -----------
    pdrParams: array_like
        Array containing the fitted PDR Toolbox parameters: (chi2,nH,G0)
    wcs: WCS
        Coordinate information.
    wcsMinMax: array_like
        Min/max pixel values of each property. This
        is used to spatially crop the WCS.
    raCenter/decCenter: float
        The center of the object in degrees.
    objectName: str
        Name of the object.
    plotTitle: str
        Title of the entire plot.
    saveFileName: str
        Pathway and name of file to save the PDF.
    cmapMinMax: array_like
        Min/max values of n and G
    """
    matplotlib.rcParams['xtick.labelsize'] = 3
    matplotlib.rcParams['ytick.labelsize'] = 3
    matplotlib.rcParams['axes.labelsize'] = 3

    # Shape of the 2D spatial array.
    nCols, nRows = pdrParams[0, :, :].shape[0], pdrParams[0, :, :].shape[1]

    fig = plt.figure(figsize=(6, 7))
    # Grid helper
    grid_helper = pywcsgrid2.GridHelper(wcs=wcs)
    # Setup the grid for plotting.
    nrows_ncols = (4, 3)

    grid = AxesGrid(fig,
                    111,
                    nrows_ncols=nrows_ncols,
                    axes_pad=(0.35, 0.07),
                    cbar_mode='each',
                    cbar_location='right',
                    cbar_pad=0,
                    axes_class=(pywcsgrid2.Axes,
                                dict(grid_helper=grid_helper)),
                    share_all=True)

    for count in range(len(pdrParams)):
        # Get the axis.
        ax = grid[count]

        # Create the colormap.
        cmap = matplotlib.cm.rainbow
        cmap.set_bad('black', 1.)  # Set masked pixels to be black.

        # Get the slice to plot
        image = pdrParams[count, :, :]

        # Plot the image
        if cmapMinMax != None:
            if count in [1, 4, 7, 10]:
                vMin, vMax = cmapMinMax[0], cmapMinMax[1]
                im = ax.imshow(image, cmap=cmap, vmin=vMin, vmax=vMax)
            elif count in [2, 5, 8, 11]:
                vMin, vMax = cmapMinMax[2], cmapMinMax[3]
                im = ax.imshow(image, cmap=cmap, vmin=vMin, vmax=vMax)
            else:
                im = ax.imshow(image, cmap=cmap)
        else:
            im = ax.imshow(image, cmap=cmap)
        # Label the ratio used inside the subplot.
        labelList = [
            '$X^2_{t-63-145-158}$', '$n$', '$G_0$', '$X^2_{Corr158}$',
            '$n_{corr158}$', '$G_{0,corr158}$', '$X^2_{corr63}$',
            '$n_{corr63}$', '$G_{0,corr63}$', '$X^2_{corr158-63}$',
            '$n_{corr158-63}$', '$G_{0,corr158-63}$'
        ]

        at = AnchoredText(labelList[count], loc=2, prop=dict(size=4))
        ax.add_artist(at)

        # Label the property average
        ave = '{:.2f}'.format(np.nanmean(image))
        med = '{:.2f}'.format(np.nanmedian(image))
        at1 = AnchoredText('mean: ' + ave, loc=4, prop=dict(size=3))
        at2 = AnchoredText(med, loc=3, prop=dict(size=3))
        ax.add_artist(at1)
        ax.add_artist(at2)

        # Flip the axis per convention.
        ax.invert_yaxis()

        # Mark the center of the galaxy.
        ax['fk5'].plot(raCenter,
                       decCenter,
                       markeredgewidth=.6,
                       marker='+',
                       color='k',
                       ms=5)

        # Make the tickmarks black.
        ax.tick_params(axis='both', colors='black', width=0)

        # Make a colorbar for each image.
        cax1 = grid.cbar_axes[count]
        if any([cmapMinMax == None, count in [0, 3, 6, 9]]):
            cbTickValues = np.linspace(np.amin(image),
                                       np.amax(image),
                                       5,
                                       endpoint=True).tolist()
        else:
            cbTickValues = np.linspace(vMin, vMax, 5, endpoint=True).tolist()
        cbar1 = cax1.colorbar(im, ticks=cbTickValues)  #,format='%.2e')

        if count in [0, 3, 6, 9, 8, 11]:
            cbar1.ax.set_yticklabels(
                [str('{:.2f}'.format(x)) for x in cbTickValues])
        else:
            cbar1.ax.set_yticklabels([str(int(x)) for x in cbTickValues])
        cbar1.ax.tick_params(labelsize=4)

    # Set figure title.
    fig.text(0.5, 0.9, plotTitle, ha='center', fontsize=10)

    # -------------------- #
    # Save the plot to PDF #
    # -------------------- #
    pp = PdfPages(saveFileName)
    pp.savefig(fig, bbox_inches='tight')
    pp.close()
    plt.close()
Exemplo n.º 5
0
f_xray = pyfits.open(xray_name)
header_xray = f_xray[0].header

# the second image
radio_name="radio_21cm.fits"
f_radio = pyfits.open(radio_name)
header_radio = f_radio[0].header


# grid helper to be used.
grid_helper = pywcsgrid2.GridHelperSky(wcs=header_xray)

# AxesGrid to display tow images side-by-side
fig = plt.figure(1, (6,3.5))
grid = AxesGrid(fig, (0.15, 0.15, 0.8, 0.75), nrows_ncols=(1, 2),
                axes_pad=0.1, share_all=True,
                axes_class=(pywcsgrid2.Axes, dict(grid_helper=grid_helper)))


ax1 = grid[0]

#from mpl_toolkits.axes_grid1.angle_helper import LocatorDMS
#from pywcsgrid2.axes_wcs import FormatterDMSDelta

#ax1.get_grid_helper().set_ticklabel_mode("delta", center_pixel=(50, 50))
ax1.set_ticklabel_type("delta",
                       center_pixel=(146, 139))
ax1.locator_params(nbins=3)


# use imshow for a simply image display.
def plot_av_vs_beta_grid(plot_dict,
         filename=None, levels=7,
        limits=None, poly_fit=False, contour=True,
        scale=['linear','linear']):

    ''' Plots a heat map of likelihoodelation values as a function of velocity
    width and velocity center.

    Parameters
    ----------
    cloud : cloudpy.Cloud
        If provided, properties taken from cloud.props.


    '''

    # Import external modules
    import numpy as np
    import matplotlib.pyplot as plt
    import myplotting as myplt
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid

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

    font_scale = 9
    params = {
              'figure.figsize': (3.6, 8),
              #'figure.titlesize': font_scale,
             }
    plt.rcParams.update(params)

    # Create figure instance
    fig = plt.figure()

    axes = AxesGrid(fig, (1,1,1),
                    nrows_ncols=(3, 1),
                    ngrids=3,
                    axes_pad=0.1,
                    aspect=False,
                    label_mode='L',
                    share_all=True)

    for i, cloud_name in enumerate(plot_dict):
        x = plot_dict[cloud_name]['av']
        y = plot_dict[cloud_name]['beta']

        ax = axes[i]

        if 'log' not in scale:
            ax.locator_params(nbins = 6)

        # Drop the NaNs from the images
        indices = np.where((x == x) &\
                           (y == y)
                           )
        x_nonans = x[indices]
        y_nonans = y[indices]

        ax = axes[i]

        if contour:
            if i == 0:
                if limits is None:
                    xmin = np.min(x_nonans)
                    ymin = np.min(y_nonans)
                    xmax = np.max(x_nonans)
                    ymax = np.max(y_nonans)
                    xscalar = 0.15 * xmax
                    yscalar = 0.15 * ymax
                    limits = [xmin - xscalar, xmax + xscalar,
                              ymin - yscalar, ymax + yscalar]

            contour_range = ((limits[0], limits[1]),
                             (limits[2], limits[3]))

            cmap = myplt.truncate_colormap(plt.cm.binary, 0.2, 1, 1000)

            l1 = myplt.scatter_contour(x_nonans.ravel(),
                                 y_nonans.ravel(),
                                 threshold=2,
                                 log_counts=1,
                                 levels=levels,
                                 ax=ax,
                                 #errors=x_error_nonans.ravel(),
                                 histogram2d_args=dict(bins=40,
                                                       range=contour_range),
                                 plot_args=dict(marker='o',
                                                linestyle='none',
                                                color='black',
                                                alpha=0.3,
                                                markersize=2),
                                 contour_args=dict(
                                                   #cmap=plt.cm.binary,
                                                   cmap=cmap,
                                                   #cmap=cmap,
                                                   ),
                                 )
        else:
            image = ax.errorbar(
                                x_nonans.ravel()[::100],
                                y_nonans.ravel()[::100],
                                yerr=(x_error_nonans.ravel()[::100]),
                                alpha=0.2,
                                color='k',
                                marker='^',
                                ecolor='k',
                                linestyle='None',
                                markersize=3
                                )

        c_cycle = myplt.set_color_cycle(num_colors=2, cmap_limits=[0.5, 0.7])

        if poly_fit:
            from scipy.optimize import curve_fit

            p = np.polyfit(x_nonans, y_nonans, 1)

            x_fit = np.linspace(-10, 100, 100)
            y_poly_fit = p[0] * x_fit + p[1]
            ax.plot(x_fit,
                    y_poly_fit,
                    color=c_cycle[1],
                    linestyle='-',
                    linewidth=2,
                    label=\
                        'Polynomial fit: \n' + \
                        r'$\beta$ = {0:.2f}'.format(p[0] * 100.0) + \
                        r'$\frac{{A_V}}{{100 \rm mag}}$ + {0:.2f}'.format(p[1]) + \
                        r'',
                    alpha=0.7,
                    )
        # Annotations
        #anno_xpos = 0.95

        ax.set_xscale(scale[0], nonposx = 'clip')
        ax.set_yscale(scale[1], nonposy = 'clip')

        ax.set_xlim(limits[0],limits[1])
        ax.set_ylim(limits[2],limits[3])

        # Adjust asthetics
        ax.set_ylabel(r'$\beta$')
        ax.set_xlabel(r'$A_V$ [mag]')

        if 1:
            loc = 'lower right'
        elif i == 0:
            loc = 'upper left'
        else:
            loc = 'lower left'

        ax.legend(loc=loc)

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

    if filename is not None:
        plt.draw()
        plt.savefig(filename, bbox_inches='tight', dpi=400)
Exemplo n.º 7
0
def plot_spectra(hi_spectrum,
                 hi_vel_axis,
                 hi_std_spectrum=None,
                 co_spectrum=None,
                 co_vel_axis=None,
                 gauss_fits=None,
                 limits=None,
                 filename='',
                 vel_range=None,
                 comp_num=None):
    ''' Plots a heat map of likelihoodelation values as a function of velocity
    width and velocity center.

    Parameters
    ----------
    cloud : cloudpy.Cloud
        If provided, properties taken from cloud.props.


    '''

    # Import external modules
    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid

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

    font_scale = 9
    params = {
        'figure.figsize': (3.6, 3.6 / 1.618),
        #'figure.titlesize': font_scale,
    }
    plt.rcParams.update(params)

    # Create figure instance
    fig = plt.figure()

    axes = AxesGrid(fig, (1, 1, 1),
                    nrows_ncols=(1, 1),
                    ngrids=1,
                    axes_pad=0,
                    aspect=False,
                    label_mode='L',
                    share_all=True)

    ax = axes[0]

    ax.plot(hi_vel_axis,
            hi_spectrum,
            linewidth=1.5,
            label=r'Median H$\textsc{i}$',
            drawstyle='steps-mid')

    if hi_std_spectrum is not None:
        ax.plot(
            hi_vel_axis,
            hi_std_spectrum,
            linewidth=1.5,
            linestyle='-.',
            label=r'$\sigma_{HI}$',
        )

    if gauss_fits is not None:
        ax.plot(
            hi_vel_axis,
            gauss_fits[0],
            alpha=0.4,
            linewidth=3,
            label='Fit',
        )

        label = 'Component'
        for i, comp in enumerate(gauss_fits[1]):
            if comp_num is not None and i in comp_num:
                linewidth = 2
            else:
                linewidth = 1
            ax.plot(
                hi_vel_axis,
                comp,
                linewidth=linewidth,
                linestyle='--',
                color='k',
                label=label,
            )
            label = None

    if co_spectrum is not None:
        co_scalar = np.nanmax(hi_spectrum) / 2.0
        co_spectrum = co_spectrum / np.nanmax(co_spectrum) * co_scalar
        ax.plot(co_vel_axis,
                co_spectrum,
                #color='k',
                label=r'Median $^{12}$CO $\times$' + \
                       '{0:.0f}'.format(co_scalar),
                drawstyle = 'steps-mid'
                )

    ax.axvspan(
        vel_range[0],
        vel_range[1],
        alpha=0.3,
        color='k',
    )

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

    ax.legend(loc='upper left')
    ax.set_xlabel('Velocity [km/s]')
    ax.set_ylabel(r'T$_b$ [K]')

    if filename is not None:
        plt.draw()
        plt.savefig(filename, bbox_inches='tight', dpi=100)
Exemplo n.º 8
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_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()
Exemplo n.º 11
0
header_xray = f_xray[0].header

# the second image
radio_name = "radio_21cm.fits"
f_radio = pyfits.open(radio_name)
header_radio = f_radio[0].header

# grid helper
grid_helper = pywcsgrid2.GridHelper(wcs=header_xray)

# AxesGrid to display tow images side-by-side
fig = plt.figure(1, (6, 3.5))
grid = AxesGrid(fig, (0.15, 0.15, 0.8, 0.75),
                nrows_ncols=(1, 2),
                axes_pad=0.1,
                share_all=True,
                cbar_mode="each",
                cbar_location="top",
                cbar_pad=0,
                axes_class=(pywcsgrid2.Axes, dict(grid_helper=grid_helper)))

ax1 = grid[0]
# use imshow for a simply image display.
im = ax1.imshow(f_xray[0].data,
                origin="lower",
                vmin=0.,
                cmap=cm.gray_r,
                interpolation="nearest")
im.set_clim(4.e-05, 0.00018)

ticklocs = [6, 9, 12, 15]