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)
def plot_cluster_data(data, colors=None, filename=None, show=False,
        labels=None, show_tick_labels=False, zlim=None, ylim=None, xlim=None):

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    from myplotting import scatter_contour
    import matplotlib as mpl

    n_components = data.shape[1]

    colors = mpl.cm.rainbow(colors)

    if labels is None:
        labels = ["1st eigenvector", "2nd eigenvector", "3rd eigenvector"]

    alpha = 1.0 / np.log10(data.shape[0])

    plt.clf()
    if n_components <= 2:
        fig = plt.figure(1, figsize=(4,4))
        ax = fig.add_subplot(111)
        #data[:,0] += np.abs(np.min(data[:,0]) + 1.0)

        ax.scatter(data[:, 0],
                   data[:, 1],
                   color=colors,
                   alpha=alpha)

        ax.set_xlabel(labels[0])
        ax.set_ylabel(labels[1])
        if not show_tick_labels:
            ax.xaxis.set_ticklabels([])
            ax.yaxis.set_ticklabels([])
        #ax.set_xscale('log')
        if 0:
            scatter_contour(data[:, 0],
                            data[:,1],
                                 threshold=2,
                                 log_counts=0,
                                 levels=5,
                                 ax=ax,
                                 histogram2d_args=dict(bins=50,),
                                 plot_args=dict(marker='o',
                                                linestyle='none',
                                                markeredgewidth=0,
                                                color='black',
                                                alpha=0.4,
                                                markersize=2.5,
                                                ),
                                 contour_args=dict(cmap=plt.cm.binary,)
                                 )

    elif n_components >= 3:
        #plt.figure(2, figsize=(6, 6))
        plt.clf()
        # To getter a better understanding of interaction of the dimensions
        # plot the first three PCA dimensions
        fig = plt.figure(1, figsize=(8, 6))
        ax = Axes3D(fig, elev=27, azim=-22)
        ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=colors, alpha=alpha)
        #ax.set_title("First three PCA directions")
        ax.set_xlabel(labels[0])
        ax.set_ylabel(labels[1])
        ax.set_zlabel(labels[2])
        if zlim is not None:
            ax.set_zlim(zlim)
        if xlim is not None:
            ax.set_xlim(xlim)
        if ylim is not None:
            ax.set_ylim(ylim)
        if not show_tick_labels:
            ax.w_xaxis.set_ticklabels([])
            ax.w_yaxis.set_ticklabels([])
            ax.w_zaxis.set_ticklabels([])

    if filename is not None:
        plt.savefig(filename,)# bbox_inches='tight')
    if show:
        plt.show()
Exemplo n.º 3
0
    def test_scatter_contour():

        from astropy.io import fits
        from myimage_analysis import calculate_nhi
        import mygeometry as myg
        from mycoords import make_velocity_axis

        # Parameters
        # ----------
        levels = (0.99, 0.985, 0.7)
        levels = (
            0.999,
            0.998,
            0.96,
            0.86,
            0.58,
        )
        levels = 7
        levels = np.logspace(np.log10(0.995), np.log10(0.50), 5)
        log_counts = 0
        limits = [1, 10, -3, 30]
        limits = None

        # Begin test
        # ----------
        data_dir = '/d/bip3/ezbc/perseus/data/'
        av = fits.getdata(data_dir +
                          'av/perseus_av_planck_tau353_5arcmin.fits')
        hi, hi_header = fits.getdata(data_dir + \
                          'hi/perseus_hi_galfa_cube_regrid_planckres.fits',
                          header=True)

        hi_vel_axis = make_velocity_axis(hi_header)

        nhi = calculate_nhi(
            cube=hi,
            velocity_axis=hi_vel_axis,
            velocity_range=[0, 10],
        )

        # Drop the NaNs from the images
        indices = np.where((av == av) &\
                           (nhi == nhi)
                           )

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

        fig, ax = plt.subplots()

        if limits is None:
            xmin = np.min(nhi_nonans)
            ymin = np.min(av_nonans)
            xmax = np.max(nhi_nonans)
            ymax = np.max(av_nonans)
            xscalar = 0.25 * xmax
            yscalar = 0.25 * 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(
            nhi_nonans.ravel(),
            av_nonans.ravel(),
            threshold=3,
            log_counts=log_counts,
            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,
            ),
        )

        scale = ['linear', 'linear']
        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'$N($H$\textsc{i}) \times\,10^{20}$ cm$^{-2}$')
        ax.set_ylabel(r'$A_V$ [mag]')
        #ax.set_title(core_names[i])
        ax.legend(loc='lower right')

        plt.savefig('test_plots/test_scatter_contour.png')
Exemplo n.º 4
0
def plot_pv(x, y, x_label=None, y_label=None, filename=None, show=False):

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    from myplotting import scatter_contour
    import matplotlib as mpl

    n_components = data.shape[1]

    colors = mpl.cm.rainbow(colors)

    if labels is None:
        labels = ["1st eigenvector", "2nd eigenvector", "3rd eigenvector"]

    alpha = 1.0 / np.log10(data.shape[0])

    plt.clf()
    if n_components <= 2:
        fig = plt.figure(1, figsize=(4, 4))
        ax = fig.add_subplot(111)
        #data[:,0] += np.abs(np.min(data[:,0]) + 1.0)

        ax.scatter(data[:, 0], data[:, 1], color=colors, alpha=alpha)

        ax.set_xlabel(labels[0])
        ax.set_ylabel(labels[1])
        if not show_tick_labels:
            ax.xaxis.set_ticklabels([])
            ax.yaxis.set_ticklabels([])
        #ax.set_xscale('log')
        if 0:
            scatter_contour(data[:, 0],
                            data[:, 1],
                            threshold=2,
                            log_counts=0,
                            levels=5,
                            ax=ax,
                            histogram2d_args=dict(bins=50, ),
                            plot_args=dict(
                                marker='o',
                                linestyle='none',
                                markeredgewidth=0,
                                color='black',
                                alpha=0.4,
                                markersize=2.5,
                            ),
                            contour_args=dict(cmap=plt.cm.binary, ))

    elif n_components >= 3:
        #plt.figure(2, figsize=(6, 6))
        plt.clf()
        # To getter a better understanding of interaction of the dimensions
        # plot the first three PCA dimensions
        fig = plt.figure(1, figsize=(8, 6))
        ax = Axes3D(fig, elev=27, azim=-22)
        ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=colors, alpha=alpha)
        #ax.set_title("First three PCA directions")
        ax.set_xlabel(labels[0])
        ax.set_ylabel(labels[1])
        ax.set_zlabel(labels[2])
        if zlim is not None:
            ax.set_zlim(zlim)
        if xlim is not None:
            ax.set_xlim(xlim)
        if ylim is not None:
            ax.set_ylim(ylim)
        if not show_tick_labels:
            ax.w_xaxis.set_ticklabels([])
            ax.w_yaxis.set_ticklabels([])
            ax.w_zaxis.set_ticklabels([])

    if filename is not None:
        plt.savefig(filename, )  # bbox_inches='tight')
    if show:
        plt.show()
Exemplo n.º 5
0
    def test_scatter_contour_log():

        import myimage_analysis as myia

        # Parameters
        # ----------
        levels = (0.99, 0.985, 0.7)
        levels = (
            0.999,
            0.998,
            0.96,
            0.86,
            0.58,
        )
        levels = 7
        levels = np.logspace(np.log10(0.995), np.log10(0.50), 5)
        log_counts = 0
        limits = [1, 10, -3, 30]
        limits = None

        x = np.linspace(1, 100, 10000)
        y = x**3 + np.random.normal(10, size=10000) + 100
        y_real = x**3 + 100

        x_nonans, y_nonans = myia.mask_nans((x, y))
        scale = ['linear', 'log']

        fig, ax = plt.subplots()

        if limits is None:
            xmin = np.min(x_nonans)
            ymin = np.min(y_nonans)
            xmax = np.max(x_nonans)
            ymax = np.max(y_nonans)
            if scale[0] == 'linear':
                xscalar = 0.25 * xmax
                xlims = xmin - xscalar, xmax + xscalar
            elif scale[0] == 'log':
                xscalar = 0.25
                xlims = xmin * xscalar, xmax / xscalar
            if scale[1] == 'linear':
                yscalar = 0.25 * ymax
                ylims = ymin - yscalar, ymax + yscalar
            elif scale[1] == 'log':
                yscalar = 0.25
                ylims = ymin * yscalar, ymax / yscalar

            limits = [xlims[0], xlims[1], ylims[0], ylims[1]]

        if 1:
            bins = [
                30,
                np.logspace(np.log10(limits[2]), np.log10(limits[3]), 30),
            ]
        else:
            bins = 40

        print bins

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

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

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

        l1 = myplt.scatter_contour(
            x_nonans.ravel(),
            y_nonans.ravel(),
            threshold=3,
            log_counts=log_counts,
            levels=levels,
            ax=ax,
            extent=limits,
            histogram2d_args=dict(
                bins=bins,
                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,
            ),
        )

        ax.plot(x, y_real, color='r', alpha=0.5, linewidth=2)

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

        # Adjust asthetics
        ax.set_xlabel(r'x')
        ax.set_ylabel(r'y')
        #ax.set_title(core_names[i])
        ax.legend(loc='lower right')

        plt.savefig('test_plots/test_scatter_contour_log.png')
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 test_scatter_contour():

        from astropy.io import fits
        from myimage_analysis import calculate_nhi
        import mygeometry as myg
        from mycoords import make_velocity_axis


        # Parameters
        # ----------
        levels = (0.99, 0.985, 0.7)
        levels = (0.999, 0.998, 0.96, 0.86, 0.58,)
        levels = 7
        levels = np.logspace(np.log10(0.995), np.log10(0.50), 5)
        log_counts = 0
        limits = [1, 10, -3, 30]
        limits = None

        # Begin test
        # ----------
        data_dir = '/d/bip3/ezbc/perseus/data/'
        av = fits.getdata(data_dir + 'av/perseus_av_planck_tau353_5arcmin.fits')
        hi, hi_header = fits.getdata(data_dir + \
                          'hi/perseus_hi_galfa_cube_regrid_planckres.fits',
                          header=True)

        hi_vel_axis = make_velocity_axis(hi_header)

        nhi = calculate_nhi(cube=hi,
                            velocity_axis=hi_vel_axis,
                            velocity_range=[0, 10],
                            )

        # Drop the NaNs from the images
        indices = np.where((av == av) &\
                           (nhi == nhi)
                           )

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

        fig, ax = plt.subplots()

        if limits is None:
            xmin = np.min(nhi_nonans)
            ymin = np.min(av_nonans)
            xmax = np.max(nhi_nonans)
            ymax = np.max(av_nonans)
            xscalar = 0.25 * xmax
            yscalar = 0.25 * 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(nhi_nonans.ravel(),
                             av_nonans.ravel(),
                             threshold=3,
                             log_counts=log_counts,
                             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,
                                               ),
                             )

        scale = ['linear', 'linear']
        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'$N($H$\textsc{i}) \times\,10^{20}$ cm$^{-2}$')
        ax.set_ylabel(r'$A_V$ [mag]')
        #ax.set_title(core_names[i])
        ax.legend(loc='lower right')

        plt.savefig('test_plots/test_scatter_contour.png')
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)
Exemplo n.º 9
0
    def test_scatter_contour_log():

        import myimage_analysis as myia

        # Parameters
        # ----------
        levels = (0.99, 0.985, 0.7)
        levels = (0.999, 0.998, 0.96, 0.86, 0.58,)
        levels = 7
        levels = np.logspace(np.log10(0.995), np.log10(0.50), 5)
        log_counts = 0
        limits = [1, 10, -3, 30]
        limits = None

        x = np.linspace(1, 100, 10000)
        y = x**3 + np.random.normal(10, size=10000) + 100
        y_real = x**3 + 100

        x_nonans, y_nonans = myia.mask_nans((x,y))
        scale = ['linear', 'log']

        fig, ax = plt.subplots()

        if limits is None:
            xmin = np.min(x_nonans)
            ymin = np.min(y_nonans)
            xmax = np.max(x_nonans)
            ymax = np.max(y_nonans)
            if scale[0] == 'linear':
                xscalar = 0.25 * xmax
                xlims = xmin - xscalar, xmax + xscalar
            elif scale[0] == 'log':
                xscalar = 0.25
                xlims = xmin * xscalar, xmax / xscalar
            if scale[1] == 'linear':
                yscalar = 0.25 * ymax
                ylims = ymin - yscalar, ymax + yscalar
            elif scale[1] == 'log':
                yscalar = 0.25
                ylims = ymin * yscalar, ymax / yscalar

            limits = [xlims[0], xlims[1], ylims[0], ylims[1]]

        if 1:
            bins = [30, np.logspace(np.log10(limits[2]),
                                    np.log10(limits[3]),
                                    30),
                    ]
        else:
            bins = 40

        print bins

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

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

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

        l1 = myplt.scatter_contour(x_nonans.ravel(),
                             y_nonans.ravel(),
                             threshold=3,
                             log_counts=log_counts,
                             levels=levels,
                             ax=ax,
                             extent=limits,
                             histogram2d_args=dict(bins=bins,
                                                   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,
                                               ),
                             )

        ax.plot(x, y_real, color='r', alpha=0.5, linewidth=2)

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

        # Adjust asthetics
        ax.set_xlabel(r'x')
        ax.set_ylabel(r'y')
        #ax.set_title(core_names[i])
        ax.legend(loc='lower right')

        plt.savefig('test_plots/test_scatter_contour_log.png')