Exemplo n.º 1
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)
def plot_diffuseLOS_map(header=None,
                        av_image=None,
                        df=None,
                        core_dict=None,
                        limits=None,
                        filename=None,
                        vlimits=(None, None),
                        contours=None,
                        parameter='phi_cnm',
                        models=['krumholz', 'sternberg']):

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

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

    # Color map
    cmap = plt.cm.copper

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

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

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

    parameters = [
        'fraction_diffuse',
    ]

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

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

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

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

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

        ax.locator_params(nbins=4)

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

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

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

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

            collection.set_array(np.array(collection_values))

        ax.add_collection(collection, )

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

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight', dpi=600)
Exemplo n.º 4
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_diffuseLOS_map(header=None, av_image=None, df=None, core_dict=None,
        limits=None, filename=None, vlimits=(None,None), contours=None,
        parameter='phi_cnm', models=['krumholz', 'sternberg']):

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

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

    # Color map
    cmap = plt.cm.copper

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

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


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

    parameters = ['fraction_diffuse',]

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

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

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

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

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

        ax.locator_params(nbins=4)

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

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

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

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

            collection.set_array(np.array(collection_values))

        ax.add_collection(collection,
                          )

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

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

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

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

    # Color map
    cmap = plt.cm.copper

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

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

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

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

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

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

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

        ax.locator_params(nbins=4)

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

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

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

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

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

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight', dpi=100)
def plot_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)
def plot_params_map(header=None, av_image=None, df=None, limits=None,
        filename=None, vlimits=(None,None), contours=None, parameter='phi_cnm'):

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

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

    # Color map
    cmap = plt.cm.copper

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

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

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

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

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

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

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

        ax.locator_params(nbins=4)

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

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

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

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

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

    if filename is not None:
        plt.savefig(filename, bbox_inches='tight', dpi=100)
Exemplo n.º 9
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.º 11
0
def plot_cores_map(
    header=None,
    contour_image=None,
    av_image=None,
    cores=None,
    cores_to_keep=None,
    props=None,
    cloud_dict=None,
    regions=None,
    title=None,
    limits=None,
    contours=None,
    boxes=False,
    savedir='./',
    filename=None,
    show=True,
    hi_vlimits=None,
    av_vlimits=None,
):

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

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

    # Color map
    cmap = plt.cm.gnuplot

    import myplotting as myplt
    cmap = myplt.truncate_colormap(plt.cm.copper, minval=0.2)

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

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

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

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

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

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

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

    ax.locator_params(nbins=6)

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

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

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

    # Plot cores for each cloud
    # -------------------------
    count = 0
    rects = []
    core_labels = []
    for i, cloud in enumerate(cloud_dict):

        cores = cloud_dict[cloud]['cores']

        cores_in_cloud = []

        for core in cores_to_keep:
            if core in cores:
                cores_in_cloud.append(core)

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

            anno_color = (0.3, 0.5, 1)

            if 0:
                ax.scatter(pix_coords[0],
                           pix_coords[1],
                           color='w',
                           s=100,
                           marker='+',
                           linewidths=1.5)

            try:

                vertices = np.copy(cores[core]['poly_verts']['pixel'])

                #[:, ::-1]
                rects.append(
                    ax.add_patch(
                        Polygon(vertices[:, ::-1],
                                facecolor='none',
                                edgecolor='w')))
                core_labels.append(str(count) + ' - ' + core)

                n = float(vertices.shape[0])
                center_xy = (np.sum(vertices[:, 1]) / n,
                             np.sum(vertices[:, 0]) / n)

                if core == 'L1521':
                    center_xy += np.array((1, 7))

                ax.annotate(
                    str(count),
                    #xy=[pix_coords[0], pix_coords[1]],
                    xy=center_xy,
                    xytext=(-4, -4),
                    label=core,
                    textcoords='offset points',
                    fontsize=font_scale * 0.75,
                    color='k',
                    path_effects=[
                        PathEffects.withStroke(linewidth=2, foreground="w")
                    ])

                count += 1
            except KeyError:
                pass

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

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

    ax.legend(rects,
              core_labels,
              loc='lower right',
              ncol=2,
              columnspacing=0.01,
              handlelength=0.1)

    if title is not None:
        fig.suptitle(title, fontsize=font_scale)
    if filename is not None:
        plt.savefig(savedir + filename, bbox_inches='tight')
    if show:
        fig.show()
def plot_cores_map(header=None, contour_image=None, av_image=None, cores=None,
        cores_to_keep=None,
        props=None, cloud_dict=None, regions=None, title=None, limits=None,
        contours=None, boxes=False, savedir='./', filename=None, show=True,
        hi_vlimits=None, av_vlimits=None,):

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

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

    # Color map
    cmap = plt.cm.gnuplot

    import myplotting as myplt
    cmap = myplt.truncate_colormap(plt.cm.copper, minval=0.2)

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

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

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

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

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

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

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

    ax.locator_params(nbins=6)

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

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

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


    # Plot cores for each cloud
    # -------------------------
    count = 0
    rects = []
    core_labels = []
    for i, cloud in enumerate(cloud_dict):

        cores = cloud_dict[cloud]['cores']

        cores_in_cloud = []

        for core in cores_to_keep:
            if core in cores:
                cores_in_cloud.append(core)


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

            anno_color = (0.3, 0.5, 1)

            if 0:
                ax.scatter(pix_coords[0],pix_coords[1],
                        color='w',
                        s=100,
                        marker='+',
                        linewidths=1.5)

            try:

                vertices = np.copy(cores[core]['poly_verts']['pixel'])

                #[:, ::-1]
                rects.append(ax.add_patch(Polygon(
                                vertices[:, ::-1],
                                facecolor='none',
                                edgecolor='w')
                                )
                            )
                core_labels.append(str(count) + ' - ' + core)

                n = float(vertices.shape[0])
                center_xy = (np.sum(vertices[:, 1]) / n,
                             np.sum(vertices[:, 0]) / n)

                if core == 'L1521':
                    center_xy += np.array((1, 7))

                ax.annotate(str(count),
                        #xy=[pix_coords[0], pix_coords[1]],
                        xy=center_xy,
                        xytext=(-4,-4),
                        label=core,
                        textcoords='offset points',
                        fontsize=font_scale*0.75,
                        color='k',
                        path_effects=[PathEffects.withStroke(linewidth=2,
                                                 foreground="w")])

                count += 1
            except KeyError:
                pass


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

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

    ax.legend(rects,
              core_labels,
              loc='lower right',
              ncol=2,
              columnspacing=0.01,
              handlelength=0.1)

    if title is not None:
        fig.suptitle(title, fontsize=font_scale)
    if filename is not None:
        plt.savefig(savedir + filename, bbox_inches='tight')
    if show:
        fig.show()
Exemplo n.º 13
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')