Exemplo n.º 1
0
def contour_hess(ax, c, m, xlim, ylim,
                 threshold=20, levels=10, bins=100, log_counts=True,
                 plot_args=None, contour_args=None):
    """Plot a CMD as a contour Hess diagram in high-density regions, and
    as a scatter plot in low density regions.

    Parameters
    ----------
    ax :
        The matplotlib Axes instance.
    c : ndarray
        The colour (x) coordinates of stars
    m : ndarray
        The magnitude (y) coordinates of stars
    """
    default_plot_args = {'ms': 2.0, 'mfc': 'k', 'mec': 'None',
                         'rasterized': True, 'alpha': 0.3}
    if plot_args is not None:
        default_plot_args.update(plot_args)

    default_contour_args = {'cmap': mpl.cm.gray_r,
                            'linestyles': 'None',
                            'linewidths': 0.,
                            'alpha': 1.}
    if contour_args is not None:
        default_contour_args.append(contour_args)

    scatter_contour(c, m, levels=levels, threshold=threshold,
                    log_counts=log_counts,
                    histogram2d_args={'bins': bins,
                                      'range': [[min(xlim), max(xlim)],
                                                [min(ylim), max(ylim)]]},
                    plot_args=default_plot_args,
                    contour_args=default_contour_args,
                    ax=ax)
Exemplo n.º 2
0
def contour_hess(ax,
                 c,
                 m,
                 xlim,
                 ylim,
                 threshold=20,
                 levels=10,
                 bins=100,
                 log_counts=True,
                 plot_args=None,
                 contour_args=None):
    """Plot a CMD as a contour Hess diagram in high-density regions, and
    as a scatter plot in low density regions.

    Parameters
    ----------
    ax :
        The matplotlib Axes instance.
    c : ndarray
        The colour (x) coordinates of stars
    m : ndarray
        The magnitude (y) coordinates of stars
    """
    default_plot_args = {
        'ms': 2.0,
        'mfc': 'k',
        'mec': 'None',
        'rasterized': True,
        'alpha': 0.3
    }
    if plot_args is not None:
        default_plot_args.update(plot_args)

    default_contour_args = {
        'cmap': mpl.cm.gray_r,
        'linestyles': 'None',
        'linewidths': 0.,
        'alpha': 1.
    }
    if contour_args is not None:
        default_contour_args.append(contour_args)

    scatter_contour(c,
                    m,
                    levels=levels,
                    threshold=threshold,
                    log_counts=log_counts,
                    histogram2d_args={
                        'bins': bins,
                        'range': [[min(xlim), max(xlim)],
                                  [min(ylim), max(ylim)]]
                    },
                    plot_args=default_plot_args,
                    contour_args=default_contour_args,
                    ax=ax)
Exemplo n.º 3
0
def hist2dscatter(x, y, nbins, threshold_value, axis=None, ms=0.5):
    if axis == None:
        axis = plt.gca()
    scatter_contour(x,
                    y,
                    threshold=threshold_value,
                    log_counts=True,
                    ax=axis,
                    histogram2d_args=dict(bins=nbins),
                    plot_args=dict(marker='.',
                                   markersize=ms,
                                   linestyle='none',
                                   color=plt.cm.plasma.colors[0]),
                    contour_args=dict(cmap=plt.cm.plasma))
Exemplo n.º 4
0
def plotcmd(cpath, txt, blue='f475w', red='f814w', y='f814w'):
    aestheticize()
    df = pd.read_hdf('hlsp/final_cut.hdf5', key='data')
    f1 = blue.lower() + '_vega'
    f2 = red.lower() + '_vega'
    f3 = y.lower() + '_vega'
    inpath = cpath.contains_points(
        np.array([df['ra'].values, df['dec'].values]).astype(float).T)
    nstars = inpath.sum()
    if nstars == 0:
        raise Exception('Nothing found in image region.')
    print('Number of stars found in region: {}'.format(nstars))
    df_cut = df[inpath]
    if df_cut.shape[0] == 0:
        raise Exception('Empty dataframe.')
    fig, ax = plt.subplots(1, 1, figsize=(6, 4.5))
    ax.plot(df_cut[f1] - df_cut[f2], df_cut[f3], 'k.', ms=4, alpha=0.)
    xl = ax.get_xlim()
    yl = ax.get_ylim()
    sc = scatter_contour(df_cut[f1] - df_cut[f2],
                         df_cut[f3],
                         ax=ax,
                         threshold=100,
                         log_counts=False,
                         plot_args={
                             'color': 'k',
                             'alpha': 0.2
                         },
                         histogram2d_args={'bins': 40},
                         contour_args={
                             'cmap': 'viridis',
                             'zorder': 100
                         })
    levels = sc[-1].levels
    labels = ['Fewer\nstars', 'More\nstars']
    cb = fig.colorbar(sc[-1])
    cb.set_ticks([levels[0], levels[-1]])
    cb.set_ticklabels(labels)
    ax.set_xlim(xl)
    ax.set_ylim(yl)
    ax.invert_yaxis()
    ax.set_xlabel('{} - {}'.format(blue.upper(), red.upper()))
    ax.set_ylabel('{}'.format(y.upper()))
    title_str = txt.split(': ')[1].split('. ')[0]
    coo = SkyCoord(*cpath.vertices[0], unit='deg')
    coo_str = coo.to_string('hmsdms')
    ax.set_title('{} ({})'.format(title_str, coo_str))
    fig.tight_layout()
    fig.set_dpi(300)
    fig.savefig('cmd.png', dpi=300)
def plot_avmod_vs_av(avmod_images, av_datas, av_error_datas=None, limits=None,
        fit=True, savedir='./', filename=None, show=True,
        scale=('linear','linear'), title = '', gridsize=(100,100), std=None):

    # import external modules
    import numpy as np
    import math
    import matplotlib.pyplot as plt
    import matplotlib
    from mpl_toolkits.axes_grid1 import ImageGrid
    from matplotlib import cm
    from astroML.plotting import scatter_contour

    n = int(np.ceil(len(av_datas)**0.5))
    if n**2 - n > len(av_datas):
        nrows = n - 1
        ncols = n
        y_scaling = 1.0 - 1.0 / n
    else:
        nrows, ncols = n, n
        y_scaling = 1.0

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

    # color map
    cmap = plt.cm.gnuplot

    # color cycle, grabs colors from cmap
    color_cycle = [cmap(i) for i in np.linspace(0, 0.8, 2)]
    params = {'axes.color_cycle': color_cycle, # colors of different plots
             }
    #plt.rcparams.update(params)

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

    imagegrid = ImageGrid(fig, (1,1,1),
                 nrows_ncols=(nrows, ncols),
                 ngrids=len(av_datas),
                 axes_pad=0.25,
                 aspect=False,
                 label_mode='L',
                 share_all=True,
                 #cbar_mode='single',
                 cbar_pad=0.1,
                 cbar_size=0.2,
                 )

    # Cycle through lists
    for i in xrange(len(av_datas)):
        av = av_datas[i]
        avmod = avmod_images[i]
        av_error_data = av_error_datas[i]

        # Drop the NaNs from the images
        if type(av_error_data) is float:
            indices = np.where((av == av) &\
                               (avmod == avmod)
                               )

        if type(av_error_data) is np.ndarray or \
                type(av_error_data) is np.ma.core.MaskedArray or \
                type(avmod_error) is np.ndarray or \
                type(avmod_error) is np.ma.core.MaskedArray:
            indices = np.where((av == av) &\
                               (avmod == avmod) &\
                               (av_error_data == av_error_data)
                               )

        av_nonans = av[indices]
        avmod_nonans = avmod[indices]

        # Fix error data types
        if type(av_error_data) is np.ndarray:
            av_error_data_nonans = av_error_data[indices]
        else:
            av_error_data_nonans = np.array(av_error_data[indices])

        # Create plot
        ax = imagegrid[i]

        if 0:
            image = ax.errorbar(av_nonans.ravel(),
                    avmod_nonans.ravel(),
                    xerr=(av_error_data_nonans.ravel()),
                    alpha=0.2,
                    color='k',
                    marker='^',
                    ecolor='k',
                    linestyle='None',
                    markersize=3
                    )
        if 0:
            image = ax.hexbin(av_nonans.ravel(),
                avmod_nonans.ravel(),
                #norm=matplotlib.colors.LogNorm(),
                mincnt=1,
                yscale=scale[1],
                xscale=scale[0],
                gridsize=gridsize,
                cmap=cm.Greys,
                #cmap=cm.gist_stern,
                )
            cb = ax.cax.colorbar(image,)
            # Write label to colorbar
            cb.set_label_text('Bin Counts',)
        if 1:
            l1 = scatter_contour(av_nonans.ravel(),
                                 avmod_nonans.ravel(),
                                 threshold=2,
                                 log_counts=0,
                                 levels=5,
                                 ax=ax,
                                 histogram2d_args=dict(bins=30,
                                        range=((limits[0], limits[1]),
                                               (limits[2], limits[3]))),
                                 plot_args=dict(marker='o',
                                                linestyle='none',
                                                color='black',
                                                alpha=0.7,
                                                markersize=2),
                                 contour_args=dict(
                                                   cmap=plt.cm.gray_r,
                                                   #cmap=cmap,
                                                   ),
                                 )



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

        # Plot 1 to 1 pline
        ax.plot((0, 10),
                (0, 10),
                color='0.5',
                linewidth=3,
                alpha=0.5)
        if std is not None:
            ax.fill_between((-std, 10),
                            (0, 10 + std),
                            (-2*std, 10 - std),
                            color='0.2',
                            alpha=0.2,
                            edgecolor='none'
                            )

        # Annotations
        anno_xpos = 0.95

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

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

        # Adjust asthetics
        ax.set_xlabel(r'$A_V$ Data [mag]')
        ax.set_ylabel(r'$A_V$ Model [mag]')
        #ax.set_title(core_names[i])

    if filename is not None:
        plt.savefig(savedir + filename)
    if show:
        fig.show()
Exemplo n.º 6
0
# Fetch the Stripe 82 standard star catalog

data = fetch_sdss_S82standards()

g = data['mmu_g']
r = data['mmu_r']
i = data['mmu_i']

#------------------------------------------------------------
# plot the results
ax = plt.axes()
scatter_contour(g - r,
                r - i,
                threshold=200,
                log_counts=True,
                ax=ax,
                histogram2d_args=dict(bins=40),
                plot_args=dict(marker='.',
                               linestyle='none',
                               markersize=1,
                               color='black'),
                contour_args=dict(cmap=plt.cm.bone))

ax.set_xlabel('g - r')
ax.set_ylabel('r - i')

ax.set_xlim(-0.5, 2.5)
ax.set_ylim(-0.5, 2.5)

plt.show()
def plot_avmod_vs_av(avmod_images,
                     av_datas,
                     av_error_datas=None,
                     limits=None,
                     fit=True,
                     savedir='./',
                     filename=None,
                     show=True,
                     scale=('linear', 'linear'),
                     title='',
                     gridsize=(100, 100),
                     std=None):

    # import external modules
    import numpy as np
    import math
    import matplotlib.pyplot as plt
    import matplotlib
    from mpl_toolkits.axes_grid1 import ImageGrid
    from matplotlib import cm
    from astroML.plotting import scatter_contour

    n = int(np.ceil(len(av_datas)**0.5))
    if n**2 - n > len(av_datas):
        nrows = n - 1
        ncols = n
        y_scaling = 1.0 - 1.0 / n
    else:
        nrows, ncols = n, n
        y_scaling = 1.0

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

    # color map
    cmap = plt.cm.gnuplot

    # color cycle, grabs colors from cmap
    color_cycle = [cmap(i) for i in np.linspace(0, 0.8, 2)]
    params = {
        'axes.color_cycle': color_cycle,  # colors of different plots
    }
    #plt.rcparams.update(params)

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

    imagegrid = ImageGrid(
        fig,
        (1, 1, 1),
        nrows_ncols=(nrows, ncols),
        ngrids=len(av_datas),
        axes_pad=0.25,
        aspect=False,
        label_mode='L',
        share_all=True,
        #cbar_mode='single',
        cbar_pad=0.1,
        cbar_size=0.2,
    )

    # Cycle through lists
    for i in xrange(len(av_datas)):
        av = av_datas[i]
        avmod = avmod_images[i]
        av_error_data = av_error_datas[i]

        # Drop the NaNs from the images
        if type(av_error_data) is float:
            indices = np.where((av == av) &\
                               (avmod == avmod)
                               )

        if type(av_error_data) is np.ndarray or \
                type(av_error_data) is np.ma.core.MaskedArray or \
                type(avmod_error) is np.ndarray or \
                type(avmod_error) is np.ma.core.MaskedArray:
            indices = np.where((av == av) &\
                               (avmod == avmod) &\
                               (av_error_data == av_error_data)
                               )

        av_nonans = av[indices]
        avmod_nonans = avmod[indices]

        # Fix error data types
        if type(av_error_data) is np.ndarray:
            av_error_data_nonans = av_error_data[indices]
        else:
            av_error_data_nonans = np.array(av_error_data[indices])

        # Create plot
        ax = imagegrid[i]

        if 0:
            image = ax.errorbar(av_nonans.ravel(),
                                avmod_nonans.ravel(),
                                xerr=(av_error_data_nonans.ravel()),
                                alpha=0.2,
                                color='k',
                                marker='^',
                                ecolor='k',
                                linestyle='None',
                                markersize=3)
        if 0:
            image = ax.hexbin(
                av_nonans.ravel(),
                avmod_nonans.ravel(),
                #norm=matplotlib.colors.LogNorm(),
                mincnt=1,
                yscale=scale[1],
                xscale=scale[0],
                gridsize=gridsize,
                cmap=cm.Greys,
                #cmap=cm.gist_stern,
            )
            cb = ax.cax.colorbar(image, )
            # Write label to colorbar
            cb.set_label_text('Bin Counts', )
        if 1:
            l1 = scatter_contour(
                av_nonans.ravel(),
                avmod_nonans.ravel(),
                threshold=2,
                log_counts=0,
                levels=5,
                ax=ax,
                histogram2d_args=dict(bins=30,
                                      range=((limits[0], limits[1]),
                                             (limits[2], limits[3]))),
                plot_args=dict(marker='o',
                               linestyle='none',
                               color='black',
                               alpha=0.7,
                               markersize=2),
                contour_args=dict(cmap=plt.cm.gray_r,
                                  #cmap=cmap,
                                  ),
            )

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

        # Plot 1 to 1 pline
        ax.plot((0, 10), (0, 10), color='0.5', linewidth=3, alpha=0.5)
        if std is not None:
            ax.fill_between((-std, 10), (0, 10 + std), (-2 * std, 10 - std),
                            color='0.2',
                            alpha=0.2,
                            edgecolor='none')

        # Annotations
        anno_xpos = 0.95

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

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

        # Adjust asthetics
        ax.set_xlabel(r'$A_V$ Data [mag]')
        ax.set_ylabel(r'$A_V$ Model [mag]')
        #ax.set_title(core_names[i])

    if filename is not None:
        plt.savefig(savedir + filename)
    if show:
        fig.show()
Exemplo n.º 8
0
# Note that with usetex=True, fonts are rendered with LaTeX.  This may
# result in an error if LaTeX is not installed on your system.  In that case,
# you can set usetex to False.
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)

#------------------------------------------------------------
# Fetch the Stripe 82 standard star catalog

data = fetch_sdss_S82standards()

g = data['mmu_g']
r = data['mmu_r']
i = data['mmu_i']

#------------------------------------------------------------
# plot the results
fig, ax = plt.subplots(figsize=(5, 3.75))
scatter_contour(g - r, r - i, threshold=200, log_counts=True, ax=ax,
                histogram2d_args=dict(bins=40),
                plot_args=dict(marker=',', linestyle='none', color='black'),
                contour_args=dict(cmap=plt.cm.bone))

ax.set_xlabel(r'${\rm g - r}$')
ax.set_ylabel(r'${\rm r - i}$')

ax.set_xlim(-0.6, 2.5)
ax.set_ylim(-0.6, 2.5)

plt.show()
def plot_av_vs_nhi(
    nhi,
    av,
    av_error=None,
    limits=None,
    fit=True,
    savedir="",
    filename=None,
    show=True,
    fit_params=None,
    contour_plot=True,
    scale=("linear", "linear"),
    title="",
    gridsize=(100, 100),
    std=None,
):

    # import external modules
    import numpy as np
    import math
    import matplotlib.pyplot as plt
    import matplotlib
    from mpl_toolkits.axes_grid1 import ImageGrid
    from matplotlib import cm
    from astroML.plotting import scatter_contour

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

    # color map
    cmap = plt.cm.gnuplot

    # color cycle, grabs colors from cmap
    color_cycle = [cmap(i) for i in np.linspace(0, 0.8, 2)]
    params = {"axes.color_cycle": color_cycle}  # colors of different plots
    # plt.rcparams.update(params)

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

    imagegrid = ImageGrid(
        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:
        indices = np.where((av == av) & (nhi == nhi))

    if type(av_error) is np.ndarray or type(av_error) is np.ma.core.MaskedArray:
        indices = np.where((av == av) & (nhi == nhi) & (av_error == av_error))

    av_nonans = av[indices]
    nhi_nonans = nhi[indices]

    # Fix error data types
    if type(av_error) is np.ndarray:
        av_error_nonans = av_error[indices]
    else:
        av_error_nonans = np.array(av_error[indices])

    # Create plot
    ax = imagegrid[0]

    if limits is not None:
        contour_range = ((limits[0], limits[1]), (limits[2], limits[3]))
    else:
        contour_range = limits

    print contour_plot
    if contour_plot:
        l1 = scatter_contour(
            nhi_nonans.ravel(),
            av_nonans.ravel(),
            threshold=2,
            log_counts=0,
            levels=5,
            ax=ax,
            histogram2d_args=dict(bins=30, range=contour_range),
            plot_args=dict(marker="o", linestyle="none", color="black", alpha=0.7, markersize=2),
            contour_args=dict(
                cmap=plt.cm.gray_r,
                # cmap=cmap,
            ),
        )
    else:
        image = ax.errorbar(
            nhi_nonans.ravel(),
            av_nonans.ravel(),
            xerr=(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:
        p = np.polyfit(nhi_nonans.ravel(), av_nonans.ravel(), deg=1)
        x_fit = np.linspace(-10, 100, 100)
        y_fit = fit_params["dgr"] * x_fit + fit_params["intercept"]
        y_poly_fit = p[0] * x_fit + p[1]
        ax.plot(
            x_fit,
            y_fit,
            # color='0.5',
            linestyle="--",
            linewidth=2,
            alpha=1,
        )
        ax.plot(x_fit, y_poly_fit, color="r", linestyle="--", linewidth=2, alpha=1)
        print ("fitted intercept = {0:.1f} mag".format(p[1]))
        std = None
        if std is not None:
            ax.fill_between((-std, 10), (0, 10 + std), (-2 * std, 10 - std), color="0.2", alpha=0.2, edgecolor="none")

    # Annotations
    anno_xpos = 0.95

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

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

    # Adjust asthetics
    ax.set_xlabel(r"$N($H$\textsc{i}) \times\,10^{20}$ cm$^{-3}$")
    ax.set_ylabel(r"$A_V$ [mag]")
    # ax.set_title(core_names[i])

    if filename is not None:
        plt.savefig(savedir + filename)
    if show:
        fig.show()
Exemplo n.º 10
0
def plot_av_vs_nhi(nhi, av, av_error=None, limits=None,
        fit=True, savedir='', filename=None, show=True, fit_params=None,
        contour_plot=True,
        scale=('linear','linear'), title = '', gridsize=(100,100), std=None):

    # import external modules
    import numpy as np
    import math
    import matplotlib.pyplot as plt
    import matplotlib
    from mpl_toolkits.axes_grid1 import ImageGrid
    from matplotlib import cm
    from astroML.plotting import scatter_contour

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

    # color map
    cmap = plt.cm.gnuplot

    # color cycle, grabs colors from cmap
    color_cycle = [cmap(i) for i in np.linspace(0, 0.8, 2)]
    params = {'axes.color_cycle': color_cycle, # colors of different plots
             }
    #plt.rcparams.update(params)

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

    imagegrid = ImageGrid(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:
        indices = np.where((av == av) &\
                           (nhi == nhi)
                           )

    if type(av_error) is np.ndarray or \
            type(av_error) is np.ma.core.MaskedArray:
        indices = np.where((av == av) &\
                           (nhi == nhi) &\
                           (av_error == av_error)
                           )

    av_nonans = av[indices]
    nhi_nonans = nhi[indices]

    # Fix error data types
    if type(av_error) is np.ndarray:
        av_error_nonans = av_error[indices]
    else:
        av_error_nonans = np.array(av_error[indices])

    # Create plot
    ax = imagegrid[0]

    if limits is not None:
        contour_range = ((limits[0], limits[1]),
                         (limits[2], limits[3]))
    else:
        contour_range = limits

    print contour_plot
    if contour_plot:
        l1 = scatter_contour(nhi_nonans.ravel(),
                             av_nonans.ravel(),
                             threshold=2,
                             log_counts=0,
                             levels=5,
                             ax=ax,
                             histogram2d_args=dict(bins=30,
                                    range=contour_range),
                             plot_args=dict(marker='o',
                                            linestyle='none',
                                            color='black',
                                            alpha=0.7,
                                            markersize=2),
                             contour_args=dict(
                                               cmap=plt.cm.gray_r,
                                               #cmap=cmap,
                                               ),
                             )
    else:
        image = ax.errorbar(nhi_nonans.ravel(),
                av_nonans.ravel(),
                xerr=(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:
        p = np.polyfit(nhi_nonans.ravel(), av_nonans.ravel(), deg=1)
        x_fit = np.linspace(-10, 100, 100)
        y_fit = fit_params['dgr'] * x_fit + fit_params['intercept']
        y_poly_fit = p[0] * x_fit + p[1]
        ax.plot(x_fit,
                y_fit,
                #color='0.5',
                linestyle='--',
                linewidth=2,
                alpha=1)
        ax.plot(x_fit,
                y_poly_fit,
                color='r',
                linestyle='--',
                linewidth=2,
                alpha=1)
        print('fitted intercept = {0:.1f} mag'.format(p[1]))
        std = None
        if std is not None:
            ax.fill_between((-std, 10),
                            (0, 10 + std),
                            (-2*std, 10 - std),
                            color='0.2',
                            alpha=0.2,
                            edgecolor='none'
                            )

    # Annotations
    anno_xpos = 0.95

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

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

    # Adjust asthetics
    ax.set_xlabel(r'$N($H$\textsc{i}) \times\,10^{20}$ cm$^{-3}$')
    ax.set_ylabel(r'$A_V$ [mag]')
    #ax.set_title(core_names[i])

    if filename is not None:
        plt.savefig(savedir + filename)
    if show:
        fig.show()
Exemplo n.º 11
0
def doAstr511HW2(truth, obs, diskLF, haloLF):
    """Make a six-panel plot illustrating Astr511 homework #2"""

    # a) Define a ``gold parallax sample" by piObs/piErr > 10 and compare distance 
    #    modulus from the parallax measurement (D/kpc=1 milliarcsec/piObs) 
    #    to the distance modulus determined from r and Mr listed in the ``truth" file 
    piObs = obs[14]
    piErr = obs[15]
    piSNR = piObs / piErr
    D = np.where(piObs>0, 1/piObs, 1.0e6) 
    mask = (piSNR>10) 
    Dok = D[mask]
    DM = 5*np.log10(Dok/0.01)
    DMtrue = truth[4] - truth[8]
    diffDM = DM - DMtrue[mask]

    if (0):
        print '  mean =', np.mean(diffDM)
        print '   rms =', np.std(diffDM)
        med, sigG = median_sigmaG(diffDM)
        print 'median =', med
        print 'sigmaG =', sigG

    ### make vectors of x=distance modulus and y=absolute magnitude to run Cminus
    # sample faint limit
    rFaintLimit = 24.5
    # use either true distances, or estimated from parallax
    if (0):
        # using "truth" values of distance modulus, DM, to compute LF
        Mr = truth[8]
        rTrue = truth[4]
        DMtrue = rTrue - Mr 
        # type could be estimated from colors...
        typeWD = truth[13]
        # here the sample is defined using true apparent magnitude
        maskC = (rTrue < rFaintLimit) & (typeWD == 1) 
        xC = DMtrue[maskC]
        yC = Mr[maskC]
    else:
        # observed apparent magnitude
        rObs = obs[6]
        if (1):
            # fit a 4-th order polynomial to Mr(gr) relation (high-SNR sample)
            A, B, C, D, E = fitPhotomParallax(truth, obs)
            # and now apply
            gr = obs[4]-obs[6]
            MrPP = WDppFit(gr, A, B, C, D, E)
        else:
            # testing here: take true Mr...
            MrPP = truth[8]
        # here the sample is defined using observed apparent magnitude
        DMobs = rObs - MrPP
        # type could be estimated from colors...
        typeWD = truth[13]
        maskC = (rObs < rFaintLimit)  & (typeWD == 1) 
        xC = DMobs[maskC]
        yC = MrPP[maskC]


    ## the sample boundary is a simple linear function because using DM
    xCmax = rFaintLimit - yC
    yCmax = rFaintLimit - xC 
    ## split disk and halo, assume populations are known
    pop = truth[14]
    popC = pop[maskC]
    maskD = (popC==1) 
    xCD = xC[maskD]
    yCD = yC[maskD]
    xCmaxD = xCmax[maskD]
    yCmaxD = yCmax[maskD]
    maskH = (popC==2) 
    xCH = xC[maskH]
    yCH = yC[maskH]
    xCmaxH = xCmax[maskH]
    yCmaxH = yCmax[maskH]

    print 'observed sample size of xCD (disk)', np.size(xCD)
    print 'observed sample size of xCH (halo)', np.size(xCH)

    ### and now corrected Mr distributions: application of the Cminus method
    ## note that Cminus returns **cumulative** distribution functions
    ## however, bootstrap_Cminus (which calls Cminus) then does conversion 
    ## and returns **differential** distribution functions 

    #### this is where we run Cminus method (or use stored results) ####
    archive_file = 'CminusZI.npz'
    if not os.path.exists(archive_file):
        print ("- computing bootstrapped differential luminosity function ")
        #------------------------------------------------------------
        # aux arrays 
        x_fit = np.linspace(0, 15, 42)
        y_fit = np.linspace(10, 17, 42)
        #------------------------------------------------------------
        ## compute the Cminus distributions (with bootstrap)
        # disk subsample 
        print ("Disk sample with %i points" % len(xCD))
        xD_dist, dxD_dist, yD_dist, dyD_dist = bootstrap_Cminus(xCD, yCD, xCmaxD, yCmaxD,
                                                    x_fit, y_fit, Nbootstraps=20, normalize=True)
        # halo subsample 
        print ("Halo sample with %i points" % len(xCH))
        xH_dist, dxH_dist, yH_dist, dyH_dist = bootstrap_Cminus(xCH, yCH, xCmaxH, yCmaxH,
                                                    x_fit, y_fit, Nbootstraps=20, normalize=True)
        np.savez(archive_file,
                 x_fit=x_fit, xD_dist=xD_dist, dxD_dist=dxD_dist,
                 y_fit=y_fit, yD_dist=yD_dist, dyD_dist=dyD_dist)
        archive_file = 'CminusZIhalo.npz'
        np.savez(archive_file,
                 xH_dist=xH_dist, dxH_dist=dxH_dist,
                 yH_dist=yH_dist, dyH_dist=dyH_dist)

        #------------------------------------------------------------
    else:
        print "- using ZI's precomputed bootstrapped luminosity function results"
        # disk
        archive_file = 'CminusZI.npz'
        archive = np.load(archive_file)
        x_fit = archive['x_fit']
        xD_dist = archive['xD_dist']
        dxD_dist = archive['dxD_dist']
        y_fit = archive['y_fit']
        yD_dist = archive['yD_dist']
        dyD_dist = archive['dyD_dist']
        # halo
        archive_file = 'CminusZIhalo.npz'
        archive = np.load(archive_file)
        xH_dist = archive['xH_dist']
        dxH_dist = archive['dxH_dist']
        yH_dist = archive['yH_dist']
        dyH_dist = archive['dyH_dist']
        
    # bin mid positions for plotting the results:
    x_mid = 0.5 * (x_fit[1:] + x_fit[:-1])
    y_mid = 0.5 * (y_fit[1:] + y_fit[:-1])


    ### determine normalization of luminosity functions and number density distributions
    ## we need to renormalize LFs: what we have are differential distributions
    ## normalized so that their cumulative LF is 1 at the last point;
    ## we need to account for the fractional sky coverage and for flux selection effect
    ## and do a bit of extrapolation to our position (DM=0) at the end
    # 1) the fraction of covered sky: we know that the sample is defined by bGal > bMin
    bMin = 60.0  # in degrees
    # in steradians, given b > 60deg, dOmega = 2*pi*[1-cos(90-60)] = 0.8418 sr
    dOmega = 2*math.radians(180)*(1-math.cos(math.radians(90-bMin)))

    # 2) renormalization constants due to selection effects
    # these correspond to the left-hand side of eq. 12 from lecture 4 (page 26)
    DMmax0 = 11.0
    MrMax0 = rFaintLimit - DMmax0
    NmaskD = ((xCD < DMmax0) & (yCD < MrMax0)) 
    Ndisk = np.sum(NmaskD)
    NmaskH = ((xCH < DMmax0) & (yCH < MrMax0)) 
    Nhalo = np.sum(NmaskH)
    print 'Size of volume-limited samples D and H:', Ndisk, ' and ', Nhalo,  '(DM<', DMmax0, ', Mr<', MrMax0, ')'
       ## Size of volume-limited samples D and H: 49791  and  2065 (DM< 11.0 , Mr< 13.5 )

    # now we need to find what fraction of the total sample (without flux selection effects)
    # is found for x < DMmax0 and y < MrMax0. To do so, we need to integrate differential 
    # distributions returned by bootstrap_Cminus up to x=DMmax0 and y=MrMax0
    # (NB: we could have EASILY read off these from the original cumulative distributions returned
    #      from Cminus, but unfortunately bootstrap_Cminus returns only differential distributions;
    #      a design bug??) 
    # n.b. verified that all four distributions integrate to 1
    XfracD = IntDiffDistr(x_fit, xD_dist, DMmax0)
    YfracD = IntDiffDistr(y_fit, yD_dist, MrMax0)
    XfracH = IntDiffDistr(x_fit, xH_dist, DMmax0)
    YfracH = IntDiffDistr(y_fit, yH_dist, MrMax0)
    # and use eq. 12 to obtain normalization constant C for both subsamples
    Cdisk = Ndisk / (XfracD * YfracD)
    Chalo = Nhalo / (XfracH * YfracH)
    print 'Cdisk = ', Cdisk, 'Chalo = ', Chalo
       ## Cdisk = 608,082  Chalo = 565,598

    ## number density normalization
    # need to go from per DM to per pc:  dDM/dV = 5 / [ln(10) * dOmega * D^3] 
    Dpc = 10 * 10**(0.2*x_mid)
    # the units are "number of stars per pc^3" (of all absolute magnitudes Mr) 
    # note that here we assume isotropic sky distribution (division by dOmega!) 
    rhoD = Cdisk * 5/np.log(10)/dOmega / Dpc**3 * xD_dist
    rhoH = Chalo * 5/np.log(10)/dOmega / Dpc**3 * xH_dist
    # same fractional errors remain after renormalization 
    dxD_distN = rhoD * dxD_dist / xD_dist
    dxH_distN = rhoH * dxH_dist / xH_dist

    # differential luminosity function: per pc3 and mag, ** at the solar position **
    # to get proper normalization, we simply multiply differential distributions (whose
    # integrals are already normalized to 1) by the local number density distributions)
    # Therefore, we need to extrapolate rhoD and rhoH to D=0
    # and then use these values as normalization factors
    # The choice of extrapolation function is tricky (much more so than in case of
    # interpolation): based on our "prior knowledge", we choose
    # for disk: fit exponential disk, ln(rho) = ln(rho0) - H*D for 100 < D/pc < 500
    xFitExpDisk = Dpc[(Dpc > 100) & (Dpc < 500)]
    yFitExpDisk = np.log(rhoD[(Dpc > 100) & (Dpc < 500)])
    A, H = curve_fit(ExpDiskDensity, xFitExpDisk, yFitExpDisk)[0]
    rhoD0 = np.exp(A) 
    print 'rhoD0', rhoD0, ' scale height H (pc) =', 1/H
    # and for halo: simply take the median value for 500 < D/pc < 2000
    rhoH0 = np.median(rhoH[(Dpc > 500) & (Dpc < 2000)])
    print 'rhoH0', rhoH0
    # and now renormalize (rhoD0, rhoH0 = 0.0047 and 0.0000217) 
    # the units are "number of stars per pc^3 AND per mag" (at D=0)
    yD_distN = yD_dist * rhoD0
    yH_distN = yH_dist * rhoH0 
    # same fractional errors remain after renormalization 
    dyD_distN = yD_distN * dyD_dist / yD_dist
    dyH_distN = yH_distN * dyH_dist / yH_dist


    ### PLOTTING ###
    plot_kwargs = dict(color='k', linestyle='none', marker='.', markersize=1)
    plt.subplots_adjust(bottom=0.09, top=0.96, left=0.09, right=0.96, wspace=0.31, hspace=0.32)

    # plot the distribution of the distance modulus difference and compute its median
    # and root-mean-square scatter (hint: beware of outliers and clip at 3sigma!)
    hist, bins = np.histogram(diffDM, bins=50)    ## N.B. diffDM defined at the top
    center = (bins[:-1]+bins[1:])/2
    ax1 = plt.subplot(3,2,1)
    ax1.plot(center, hist, drawstyle='steps')   
    ax1.set_xlim(-1, 1)
    ax1.set_xlabel(r'$\mathrm{\Delta DM (mag)}$')
    ax1.set_ylabel(r'$\mathrm{dN/d(\Delta DM)}$')
    ax1.set_title('parallax SNR>10')
    ax1.plot(label=r'mpj legend')

    plt.text(0.25, 0.9,
         r'$\bar{x}=-0.023$',
         fontsize=12, bbox=dict(ec='k', fc='w', alpha=0.9),
         ha='center', va='center', transform=plt.gca().transAxes)
    plt.text(0.75, 0.9,
         r'$med.=-0.035$',
         fontsize=12, bbox=dict(ec='k', fc='w', alpha=0.9),
         ha='center', va='center', transform=plt.gca().transAxes)
    plt.text(0.2, 0.7,
         r'$\sigma=0.158$',
         fontsize=12, bbox=dict(ec='k', fc='w', alpha=0.9),
         ha='center', va='center', transform=plt.gca().transAxes)
    plt.text(0.75, 0.7,
         r'$\sigma_G=0.138$',
         fontsize=12, bbox=dict(ec='k', fc='w', alpha=0.9),
         ha='center', va='center', transform=plt.gca().transAxes)


    # plot uncorrected Mr vs. DM for disk
    ax2 = plt.subplot(3,2,2)
    ax2.set_xlim(4, 15)
    ax2.set_ylim(17, 10)
    ax2.set_xlabel(r'$\mathrm{DM}$')
    ax2.set_ylabel(r'$\mathrm{M_{r}}$')
    scatter_contour(xCD, yCD, threshold=20, log_counts=True, ax=ax2,
                histogram2d_args=dict(bins=40),
                plot_args=dict(marker='.', linestyle='none',
                               markersize=1, color='black'),
                contour_args=dict(cmap=plt.cm.bone))
    # ax2.plot(xCmaxD, yCD, color='blue')
    plt.text(0.75, 0.20,
         r'$disk$',
         fontsize=22, bbox=dict(ec='k', fc='w', alpha=0.3),
         ha='center', va='center', transform=plt.gca().transAxes)


    # plot uncorrected Mr vs. DM for halo
    ax3 = plt.subplot(3,2,3)
    ax3.set_xlim(4, 15)
    ax3.set_ylim(17, 10)
    ax3.set_xlabel(r'$\mathrm{DM}$')
    ax3.set_ylabel(r'$\mathrm{M_{r}}$')
    scatter_contour(xCH, yCH, threshold=20, log_counts=True, ax=ax3,
                histogram2d_args=dict(bins=40),
                plot_args=dict(marker='.', linestyle='none',
                               markersize=1, color='black'),
                contour_args=dict(cmap=plt.cm.bone))
    # ax3.plot(xCH, yCmaxH, '.k', markersize=0.1, color='blue')
    plt.text(0.75, 0.20,
         r'$halo$',
         fontsize=22, bbox=dict(ec='k', fc='w', alpha=0.3),
         ha='center', va='center', transform=plt.gca().transAxes)


    # uncorrected Mr distributions 
    ax4 = plt.subplot(3,2,4)
    ax4.hist(yCD, bins=30, log=True, histtype='step', color='red')
    ax4.hist(yCH, bins=30, log=True, histtype='step', color='blue')
    ax4.set_xlim(10, 17)
    ax4.set_ylim(1, 50000)
    ax4.set_xlabel(r'$\mathrm{M_r}$')
    ax4.set_ylabel(r'$\mathrm{dN/dM_r}$')
    plt.text(0.52, 0.20,
         r'$uncorrected \, M_r \, distribution$',
         fontsize=12, bbox=dict(ec='k', fc='w', alpha=0.3),
         ha='center', va='center', transform=plt.gca().transAxes)


    ## now plot the two remaining panels: corrected rho and Mr distributions
    # density distributions
    ax5 = plt.subplot(325, yscale='log')
    ax5.errorbar(Dpc, rhoD, dxD_distN, fmt='^k', ecolor='k', lw=1, color='red', label='disk')
    ax5.errorbar(Dpc, rhoH, dxH_distN, fmt='^k', ecolor='k', lw=1, color='blue', label='halo')

    ax5.set_xlim(0, 5000)
    ax5.set_ylim(0.000001, 0.01)
    ax5.set_xlabel(r'$\mathrm{D (pc)}$')
    ax5.set_ylabel(r'$\mathrm{\rho(D)} (pc^{-3}) $')
    ax5.legend(loc='upper right')

    # luminosity functions
    ax6 = plt.subplot(326, yscale='log')
    ax6.errorbar(y_mid, yD_distN, dyD_distN, fmt='^k', ecolor='k', lw=1, color='red')
    ax6.errorbar(y_mid, yH_distN, dyH_distN, fmt='^k', ecolor='k', lw=1, color='blue')

    # true luminosity functions
    MbinD = diskLF[0]
    psiD = diskLF[1] 
    MbinH = haloLF[0]
    psiH = haloLF[1] / 200
    ax6.plot(MbinD, psiD, color='red')
    ax6.plot(MbinH, psiH, color='blue')
 
    plt.text(0.62, 0.15,
         r'$\Psi \, in \, pc^{-3} mag^{-1}$',
         fontsize=12, bbox=dict(ec='k', fc='w', alpha=0.3),
         ha='center', va='center', transform=plt.gca().transAxes)

    ax6.set_xlim(10, 17)
    ax6.set_xlabel(r'$\mathrm{M_r}$')
    ax6.set_ylabel(r'$\Psi(M_r)=\mathrm{dN^2/dV \,dM_r}$')

    plt.savefig('Astr511HW2.png')
    plt.show() 
Exemplo n.º 12
0
def print_chi(data_dict, axis):
    """ Make the chi plot 
    
    Some more doc if need be ... 
    """
    #plt.clf()
    #fig = plt.figure()
    #axis = fig.add_subplot(111)
    
    mags = data_dict['SDSS_g_mMed'] 
    chi = data_dict['delflx'] / data_dict['delflxerr']
    
    # remove silly values     
    m = ( mags > 17 ) * (mags< 20)
    mags = mags[m];  chi = chi[m]
    
    print('We throw away points with magnitude < 15, so that we are left with %d'%len(chi)+" points")    
    nlev = 15
    scatter_contour(mags, chi, levels=nlev, threshold=50, log_counts=True, ax=axis,
                    histogram2d_args=dict(bins=40), 
                    plot_args=dict(marker=' ', linestyle='none', color='black'),
                    contour_args=dict(cmap=plt.cm.jet))
                    
    step = (max(chi)-min(chi)) / nlev
    print('Colourscale ranges from %f to %f, with 15 levels, i.e. steps every %f '%\
        (min(chi), max(chi), step) ) 
        
    rms_robust = lambda x : 0.7414 *(np.percentile(x,75) - np.percentile(x,25))
    rms_std = lambda x : np.std(x)
   
   # The code below starts at 40 bins and calculates standard deviation sigma, 
   # and robust sigma G for each bin, and finds the smallest number of bins 
   # where there are no NaNs in any bin.
   
    
    nbins1 = 40
    diagnostic = 10
    while  diagnostic > 0 : 
        rms1_all = binned_statistic(mags, chi, statistic=rms_std, bins=nbins1)
        nbins1 = nbins1 - 2
        diagnostic = np.isnan(rms1_all[0]).sum() 
    print('For standard deviation we use %d bins' %nbins1)
    nbins2 = 40
    diagnostic = 10
    while  diagnostic > 0 : 
        rms2_all = binned_statistic(mags, chi, statistic=rms_robust, bins=nbins2)
        nbins2 = nbins2 - 2
        diagnostic = np.isnan(rms1_all[0]).sum()
    print('For robust sigma G we use %d bins' %nbins2)
    
    # Evaluated at the same bins as respective standard deviations... 
    bin_means1 = binned_statistic(mags, chi, statistic = 'mean', bins=nbins1+2)[0]
    bin_means2 = binned_statistic(mags, chi, statistic = 'mean', bins=nbins2+2)[0]
        
        
    chi_rms1 = rms1_all[0]
    mags1 = rms1_all[1][:-1] # number of bins is one more than that of values
    
    chi_rms2 = rms2_all[0]
    mags2 = rms2_all[1][:-1]
    
    #return mags1, mags2, bin_means1, bin_means2, chi_rms1, chi_rms2
    
    sym = 56 # symbol size 
    axis.scatter(mags1, bin_means1 + 2*chi_rms1,s=sym, alpha=1.0, color='yellow', edgecolors='black')
    axis.scatter(mags1, bin_means1 - 2*chi_rms1,s=sym, alpha=1.0, color='yellow', edgecolors='black')
    
    axis.scatter(mags2, bin_means2 + 2*chi_rms2,s=sym, alpha=1.0, color='orange', edgecolors='black' )
    axis.scatter(mags2, bin_means2 - 2*chi_rms2,s=sym, alpha=1.0, color='orange', edgecolors='black' )
          
    axis.set_xlim(xmin=17)
    axis.set_ylim(ymin=-6, ymax=6)
    axis.xaxis.set_label_position('top')
    axis.xaxis.tick_top()
    axis.set_xlabel('SDSS g mag' )
    axis.set_ylabel(r'$\chi $')
    axis.set_xticks([17,18,19,20])
    axis.set_xticklabels(['17','18','19','20'])
Exemplo n.º 13
0
def plot_L_vs_T(T,
                L,
                masses=None,
                filename=None,
                show=False,
                limits=None,
                scale=['linear', 'linear']):

    # Import external modules
    import numpy as np
    import math
    import pyfits as pf
    import matplotlib.pyplot as plt
    import matplotlib
    from mpl_toolkits.axes_grid1 import ImageGrid
    from astroML.plotting import scatter_contour

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

    # Color map
    cmap = plt.cm.gnuplot

    # Color cycle, grabs colors from cmap
    color_cycle = [cmap(i) for i in np.linspace(0, 0.8, 3)]
    font_scale = 13
    line_weight = 600
    font_weight = 600

    params = {
        'axes.color_cycle': color_cycle,  # colors of different plots
        'axes.labelsize': font_scale,
        'axes.titlesize': font_scale,
        #'axes.weight': line_weight,
        'axes.linewidth': 1.2,
        'axes.labelweight': font_weight,
        'legend.fontsize': font_scale * 3 / 4,
        'xtick.labelsize': font_scale,
        'ytick.labelsize': font_scale,
        'font.weight': font_weight,
        'font.serif': 'computer modern roman',
        'text.fontsize': font_scale,
        'text.usetex': True,
        #'text.latex.preamble': r'\usepackage[T1]{fontenc}',
        #'font.family': 'sans-serif',
        'figure.figsize': (5, 5),
        'figure.dpi': 600,
        'backend': 'pdf',
        #'figure.titlesize': font_scale,
    }
    plt.rcParams.update(params)

    # Create figure instance
    fig = plt.figure()

    ax = fig.add_subplot(111)

    bins = (T[::-1], L)

    bins = 15
    L = np.log10(L)
    scale = 'linear', 'linear'
    limits = [40000, 500, -3, 6]

    l1 = scatter_contour(
        T,
        L,
        threshold=1,
        log_counts=True,
        levels=6,
        ax=ax,
        histogram2d_args=dict(
            bins=bins,
            range=((limits[1], limits[0]), (limits[2], limits[3])),
        ),
        plot_args=dict(marker='o',
                       linestyle='none',
                       color='black',
                       alpha=0.7,
                       markersize=2),
        contour_args=dict(cmap=plt.cm.gray_r,
                          #cmap=cmap,
                          ),
    )

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

    ax.set_xscale(scale[0])
    ax.set_yscale(scale[1])

    # Adjust asthetics
    ax.set_xlabel(r'$T_{\rm eff}$ [K]')
    ax.set_ylabel(r'log$_{10}( L $ [L$_\odot$])')

    ax.locator_params(nbins=5, axis='x')

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight')
    if show:
        fig.show()
plt.xlim(-5.0, 5.0)
plt.ylim(-5.0, 5.0)


iplot=iplot+1
plt.subplot(2,2,iplot)
threshold=10

# note ax=plt within arguments
plt.title("scatter_contour: '.', markersize=2, color='red'")
label='data: ' + str(len(xdata))
scatter_contour(xdata, ydata, threshold=threshold, log_counts=True, 
                histogram2d_args=dict(bins=40),
                ax=plt,
                plot_args=dict(marker='.', linestyle='none',
                               markersize=2, color='red',
                               markeredgecolor='red',
                               label=label),
                contour_args=dict(cmap=plt.cm.rainbow))

plt.xlim(-5.0, 5.0)
plt.ylim(-5.0, 5.0)

iplot=iplot+1
plt.subplot(2,2,iplot)
threshold=10
plt.title("scatter_contour: 'o', markersize=2, color='blue'")
scatter_contour(xdata, ydata, threshold=threshold, log_counts=True, 
                histogram2d_args=dict(bins=20),
                ax=plt,
                plot_args=dict(marker='o', linestyle='none',
Exemplo n.º 15
0
def plot_colorcolor():

    # ADD MW SATELLITES?

    # READ SPECTRA
    file = SAGA_DIR + '/data/saga_spectra_dirty.fits.gz'
    allspec = Table.read(file)

    m1 = allspec['ZQUALITY'] > 2
    m2 = allspec['REMOVE'] == -1
    allspec = allspec[m1 & m2]

    #	msat = allspec['SATS'] == 1
    msat1 = allspec['SPEC_Z'] > 0.005
    msat2 = allspec['SPEC_Z'] < 0.02
    msat = msat1 & msat2
    mname1 = allspec['SATS'] == 1
    mname2 = allspec['HOST_SAGA_NAME'] != ''
    mname = mname1 & mname2

    gr = allspec['g'] - allspec['r']
    ri = allspec['r'] - allspec['i']

    fmag = allspec['r'] > 17.7
    bmag = allspec['r'] <= 17.7

    gal = allspec['PHOTPTYPE'] == 3
    star = allspec['PHOTPTYPE'] == 6

    xl = [-0.3, 2.0]
    yl = [-0.8, 1.3]

    xl1 = gr > xl[0]
    xl2 = gr < xl[1]
    yl1 = ri > yl[0]
    yl2 = ri < yl[1]
    lims = xl1 & xl2 & yl1 & yl2

    fig = plt.figure(figsize=(7, 7))
    fig.subplots_adjust(left=0.1,
                        right=0.95,
                        wspace=0.05,
                        bottom=0.1,
                        top=0.95,
                        hspace=0.05)

    thr = 60
    ##############################
    ax = fig.add_subplot(2, 2, 1)
    scatter_contour(gr[gal & bmag & lims],
                    ri[gal & bmag & lims],
                    threshold=thr,
                    log_counts=True,
                    ax=ax,
                    histogram2d_args=dict(bins=40),
                    plot_args=dict(marker=',', linestyle='none',
                                   color='black'),
                    contour_args=dict(cmap=plt.cm.bone))

    ax.plot(gr[gal & bmag & msat], ri[gal & bmag & msat], 'b.', label='low-z')
    ax.plot(gr[gal & bmag & msat & mname],
            ri[gal & bmag & msat & mname],
            'r.',
            label='satellites')
    ax.set_xlim(xl)
    ax.set_ylim(yl)
    ax.text(xl[0] + 0.02, yl[1] - 0.2, 'Bright Galaxies, r $<$ 17.7')
    ax.get_xaxis().set_visible(False)
    plt.axvline(0.8, c='k', ls=':')
    plt.axhline(0.5, c='k', ls=':')
    plt.legend(loc=4, fontsize=9)
    ax.set_ylabel('(r-i)')

    ##############################
    ax = fig.add_subplot(2, 2, 2)
    scatter_contour(gr[gal & fmag & lims],
                    ri[gal & fmag & lims],
                    threshold=thr,
                    log_counts=True,
                    ax=ax,
                    histogram2d_args=dict(bins=40),
                    plot_args=dict(marker=',', linestyle='none',
                                   color='black'),
                    contour_args=dict(cmap=plt.cm.bone))

    ax.plot(gr[gal & fmag & msat], ri[gal & fmag & msat], 'b.')
    ax.plot(gr[gal & fmag & msat & mname], ri[gal & fmag & msat & mname], 'r.')
    ax.set_xlim(xl)
    ax.set_ylim(yl)
    ax.text(xl[0] + 0.02, yl[1] - 0.2, 'Faint Galaxies, r $>$ 17.7')
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    plt.axvline(0.8, c='k', ls=':')
    plt.axhline(0.5, c='k', ls=':')

    ##############################
    ax = fig.add_subplot(2, 2, 3)
    scatter_contour(gr[star & bmag & lims],
                    ri[star & bmag & lims],
                    threshold=thr,
                    log_counts=True,
                    ax=ax,
                    histogram2d_args=dict(bins=40),
                    plot_args=dict(marker=',', linestyle='none',
                                   color='black'),
                    contour_args=dict(cmap=plt.cm.bone))

    ax.plot(gr[star & bmag & msat], ri[star & bmag & msat], 'b.')
    ax.plot(gr[star & bmag & msat & mname], ri[star & bmag & msat & mname],
            'r.')
    ax.set_xlim(xl)
    ax.set_ylim(yl)
    ax.text(xl[0] + 0.03, yl[1] - 0.2, 'Bright Stars, r $<$ 17.7')
    plt.axvline(0.8, c='k', ls=':')
    plt.axhline(0.5, c='k', ls=':')
    ax.set_xlabel('(g-r)')
    ax.set_ylabel('(r-i)')

    ##############################
    ax = fig.add_subplot(2, 2, 4)
    scatter_contour(gr[star & fmag & lims],
                    ri[star & fmag & lims],
                    threshold=thr,
                    log_counts=True,
                    ax=ax,
                    histogram2d_args=dict(bins=40),
                    plot_args=dict(marker=',', linestyle='none',
                                   color='black'),
                    contour_args=dict(cmap=plt.cm.bone))

    ax.plot(gr[star & fmag & msat], ri[star & fmag & msat], 'b.')
    ax.plot(gr[star & fmag & msat & mname], ri[star & fmag & msat & mname],
            'r.')
    ax.set_xlim(xl)
    ax.set_ylim(yl)
    ax.text(xl[0] + 0.03, yl[1] - 0.2, 'Faint Stars, r $>$ 17.7')
    ax.get_yaxis().set_visible(False)
    plt.axvline(0.8, c='k', ls=':')
    plt.axhline(0.5, c='k', ls=':')
    ax.set_xlabel('(g-r)')

    plt.show()
    plt.savefig('fig_colorcolor.pdf')

    # DO OBJECTS OUTSIDE OF STRAIGHT COLOR REQUIRES,
    # PASS CRITERIA INCLUDING ERRORS?

    lowz = allspec[msat]

    gr = lowz['g'] - lowz['r']
    ri = lowz['r'] - lowz['i']

    m1 = gr > 0.8
    m2 = ri > 0.5
    for obj in lowz[m1 | m2]:
        gmr = obj['g'] - obj['r']
        rmi = obj['r'] - obj['i']
        gmre = obj['g'] - obj['r'] - 2 * obj['g_err'] - 2 * obj['r_err']
        rmie = obj['r'] - obj['i'] - 2 * obj['r_err'] - 2 * obj['i_err']

        #		print gmr,gmre,obj['SATS'],obj['PHOTPTYPE'],obj['SPEC_Z'],obj['REMOVE']
        #		print rmi,rmie
        if gmre > 0.8 and rmie > 0.5:
            print obj['SPEC_Z'], obj['RA'], obj['DEC'], obj['r']

    print 'STARS'
    star = lowz['PHOTPTYPE'] == 6
    for obj in lowz[star]:
        print obj['SPEC_Z'], obj['RA'], obj['DEC'], obj['TELNAME'], obj[
            'HOST_NSAID'], obj['SATS'], obj['REMOVE']
Exemplo n.º 16
0
def plot_colorcolor():


# ADD MW SATELLITES?

	# READ SPECTRA
	file = SAGA_DIR +'/data/saga_spectra_dirty.fits.gz'
	allspec = Table.read(file)

	m1 = allspec['ZQUALITY'] > 2
	m2 = allspec['REMOVE'] == -1
	allspec = allspec[m1&m2]

#	msat = allspec['SATS'] == 1
	msat1 = allspec['SPEC_Z'] > 0.005
	msat2 = allspec['SPEC_Z'] < 0.02
	msat = msat1 & msat2
	mname1 = allspec['SATS'] == 1
	mname2 = allspec['HOST_SAGA_NAME'] != ''
	mname = mname1&mname2

	gr = allspec['g'] - allspec['r']
	ri = allspec['r'] - allspec['i']



	fmag = allspec['r'] > 17.7
	bmag = allspec['r'] <= 17.7

	gal = allspec['PHOTPTYPE']  == 3
	star = allspec['PHOTPTYPE'] == 6

	xl = [-0.3,2.0]
	yl=[-0.8,1.3]

	xl1 = gr > xl[0]
	xl2 = gr < xl[1]
	yl1 = ri > yl[0]
	yl2 = ri < yl[1]
	lims = xl1&xl2&yl1&yl2

	fig = plt.figure(figsize=(7, 7))
	fig.subplots_adjust(left=0.1, right=0.95, wspace=0.05,
                    bottom=0.1, top=0.95, hspace=0.05)


	thr = 60
	##############################
	ax = fig.add_subplot(2, 2, 1)
	scatter_contour(gr[gal&bmag&lims], ri[gal&bmag&lims], threshold=thr, log_counts=True, ax=ax,
                histogram2d_args=dict(bins=40),
                plot_args=dict(marker=',', linestyle='none', color='black'),
                contour_args=dict(cmap=plt.cm.bone))


	ax.plot(gr[gal&bmag&msat], ri[gal&bmag&msat],'b.',label = 'low-z')
	ax.plot(gr[gal&bmag&msat&mname], ri[gal&bmag&msat&mname],'r.',label='satellites')
	ax.set_xlim(xl)
	ax.set_ylim(yl)
	ax.text(xl[0]+0.02,yl[1]-0.2,'Bright Galaxies, r $<$ 17.7')
	ax.get_xaxis().set_visible(False)
	plt.axvline(0.8, c='k', ls=':')
	plt.axhline(0.5, c='k', ls=':')
	plt.legend(loc=4,fontsize=9)
	ax.set_ylabel('(r-i)')

	##############################
	ax = fig.add_subplot(2, 2, 2)
	scatter_contour(gr[gal&fmag&lims], ri[gal&fmag&lims], threshold=thr, log_counts=True, ax=ax,
                histogram2d_args=dict(bins=40),
                plot_args=dict(marker=',', linestyle='none', color='black'),
                contour_args=dict(cmap=plt.cm.bone))

	ax.plot(gr[gal&fmag&msat], ri[gal&fmag&msat],'b.')
	ax.plot(gr[gal&fmag&msat&mname], ri[gal&fmag&msat&mname],'r.')
	ax.set_xlim(xl)
	ax.set_ylim(yl)
	ax.text(xl[0]+0.02,yl[1]-0.2,'Faint Galaxies, r $>$ 17.7')
	ax.get_xaxis().set_visible(False)
	ax.get_yaxis().set_visible(False)
	plt.axvline(0.8, c='k', ls=':')
	plt.axhline(0.5, c='k', ls=':')


	##############################
	ax = fig.add_subplot(2, 2, 3)
	scatter_contour(gr[star&bmag&lims], ri[star&bmag&lims], threshold=thr, log_counts=True, ax=ax,
                histogram2d_args=dict(bins=40),
                plot_args=dict(marker=',', linestyle='none', color='black'),
                contour_args=dict(cmap=plt.cm.bone))

	ax.plot(gr[star&bmag&msat], ri[star&bmag&msat],'b.')
	ax.plot(gr[star&bmag&msat&mname], ri[star&bmag&msat&mname],'r.')
	ax.set_xlim(xl)
	ax.set_ylim(yl)
	ax.text(xl[0]+0.03,yl[1]-0.2,'Bright Stars, r $<$ 17.7')
	plt.axvline(0.8, c='k', ls=':')
	plt.axhline(0.5, c='k', ls=':')
	ax.set_xlabel('(g-r)')
	ax.set_ylabel('(r-i)')

	##############################
	ax = fig.add_subplot(2, 2, 4)
	scatter_contour(gr[star&fmag&lims], ri[star&fmag&lims], threshold=thr, log_counts=True, ax=ax,
                histogram2d_args=dict(bins=40),
                plot_args=dict(marker=',', linestyle='none', color='black'),
                contour_args=dict(cmap=plt.cm.bone))

	ax.plot(gr[star&fmag&msat], ri[star&fmag&msat],'b.')
	ax.plot(gr[star&fmag&msat&mname], ri[star&fmag&msat&mname],'r.')
	ax.set_xlim(xl)
	ax.set_ylim(yl)
	ax.text(xl[0]+0.03,yl[1]-0.2,'Faint Stars, r $>$ 17.7')
	ax.get_yaxis().set_visible(False)
	plt.axvline(0.8, c='k', ls=':')
	plt.axhline(0.5, c='k', ls=':')
	ax.set_xlabel('(g-r)')

	plt.show()
	plt.savefig('fig_colorcolor.pdf')


	# DO OBJECTS OUTSIDE OF STRAIGHT COLOR REQUIRES,
	# PASS CRITERIA INCLUDING ERRORS?

	lowz = allspec[msat]

	gr = lowz['g'] - lowz['r']
	ri = lowz['r'] - lowz['i']

	m1 = gr > 0.8
	m2 = ri > 0.5
	for obj in lowz[m1|m2]:
		gmr  = obj['g'] - obj['r'] 
		rmi  = obj['r'] - obj['i'] 
		gmre  = obj['g'] - obj['r'] - 2*obj['g_err'] - 2*obj['r_err']
		rmie  = obj['r'] - obj['i'] - 2*obj['r_err'] - 2*obj['i_err']


#		print gmr,gmre,obj['SATS'],obj['PHOTPTYPE'],obj['SPEC_Z'],obj['REMOVE']
#		print rmi,rmie
		if gmre > 0.8 and rmie > 0.5:
			print obj['SPEC_Z'],obj['RA'],obj['DEC'],obj['r']


	print 'STARS'
	star = lowz['PHOTPTYPE'] ==6
	for obj in lowz[star]:
		print obj['SPEC_Z'],obj['RA'],obj['DEC'],obj['TELNAME'],obj['HOST_NSAID'],obj['SATS'],obj['REMOVE']