Ejemplo n.º 1
0
    def actin_intensity_and_density_histogram(self):
        bins = np.logspace(2**-1, np.log2(self.dmax["ring_dens_ratio"].max()),
                           1000)
        logform = ticker.LogFormatterMathtext(base=2)
        ticks = ticker.LogLocator(base=2, ).tick_values(
            2**-1, np.log2(self.dmax["ring_dens_ratio"].max()))
        labels = [logform(i) for i in ticks]

        g = sns.FacetGrid(self.dmax, hue="Compound", legend_out=True)
        g = (g.map_dataframe(_distplot, "ring_dens_ratio",
                             bins=bins).set(xscale='log').set(
                                 xticks=ticks,
                                 xticklabels=labels,
                                 xlim=(min(ticks), max(ticks))).add_legend())
        path = o.ensure_dir(
            os.path.join(self.cc.base_path, 'out', 'graphs',
                         'actinring_dens_hist_all.pdf'))
        g.savefig(path)
        plt.close()

        g = sns.FacetGrid(self.dmax,
                          row="Compound",
                          hue="Compound",
                          legend_out=True)
        g = (g.map_dataframe(_distplot, "ring_dens_ratio",
                             bins=bins).set(xscale='log').set(
                                 xticks=ticks,
                                 xticklabels=labels,
                                 xlim=(min(ticks), max(ticks))).add_legend())
        path = o.ensure_dir(
            os.path.join(self.cc.base_path, 'out', 'graphs',
                         'actinring_dens_hist_each.pdf'))
        g.savefig(path)
        plt.close()
Ejemplo n.º 2
0
def plot_dos(aedges, Rpedges, DoS, name, path=None):
    """Plots depth of search as a filled contour plot with contour lines

    Args:
        aedges (ndarray):
            1-D array of semi-major axis bin edges
        Rpedges (ndarray):
            1-D array of planetary radius bin edges
        DoS (ndarray):
            2-D array of depth-of-search values
        name (str):
            string indicating what to put in title of figure
        path (str):
            desired path to save figure (png, optional)

    """

    acents = 0.5 * (aedges[1:] + aedges[:-1])
    a = np.hstack((aedges[0], acents, aedges[-1]))
    a = np.around(a, 4)
    Rcents = 0.5 * (Rpedges[1:] + Rpedges[:-1])
    R = np.hstack((Rpedges[0], Rcents, Rpedges[-1]))
    R = np.around(R, 4)
    # extrapolate to left-most boundary
    tmp = DoS[:, 0] + (a[0] - a[1]) * ((DoS[:, 1] - DoS[:, 0]) / (a[2] - a[1]))
    DoS = np.insert(DoS, 0, tmp, axis=1)
    # extrapolate to right-most boundary
    tmp = DoS[:, -1] + (a[-1] - a[-2]) * ((DoS[:, -1] - DoS[:, -2]) /
                                          (a[-2] - a[-3]))
    DoS = np.insert(DoS, -1, tmp, axis=1)
    # extrapolate to bottom-most boundary
    tmp = DoS[0, :] + (R[0] - R[1]) * ((DoS[1, :] - DoS[0, :]) / (R[2] - R[1]))
    DoS = np.insert(DoS, 0, tmp, axis=0)
    # extrapolate to upper-most boundary
    tmp = DoS[-1, :] + (R[-1] - R[-2]) * ((DoS[-1, :] - DoS[-2, :]) /
                                          (R[-2] - R[-3]))
    DoS = np.insert(DoS, -1, tmp, axis=0)
    DoS = np.ma.masked_where(DoS <= 0.0, DoS)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cs = ax.contourf(a,
                     R,
                     DoS,
                     locator=ticker.LogLocator(),
                     levels=[1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0])
    cs2 = ax.contour(a, R, DoS, colors='k', levels=cs.levels)
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set_xlabel('a (AU)')
    ax.set_ylabel('$R_p$ ($R_\oplus$)')
    ax.set_title('Depth of Search - ' + name)
    cbar = fig.colorbar(cs)
    ax.clabel(cs2, fmt=ticker.LogFormatterMathtext(), colors='k')
    if path is not None:
        fig.savefig(path,
                    format='png',
                    dpi=100,
                    bbox_inches='tight',
                    pad_inches=0.1)
    plt.close(fig)
Ejemplo n.º 3
0
    def plot_nplan(self, targ, name, path=None):
        '''Plots depth of search convolved with occurrence rates as a filled 
        contour plot with contour lines
        
        Args:
            targ (str):
                string indicating which key to access from depth of search 
                result dictionary
            name (str):
                string indicating what to put in title of figure
            path (str):
                desired path to save figure (pdf, optional)
        
        '''

        acents = 0.5 * (self.result['aedges'][1:] + self.result['aedges'][:-1])
        a = np.hstack(
            (self.result['aedges'][0], acents, self.result['aedges'][-1]))
        a = np.around(a, 4)
        Rcents = 0.5 * (self.result['Redges'][1:] + self.result['Redges'][:-1])
        R = np.hstack(
            (self.result['Redges'][0], Rcents, self.result['Redges'][-1]))
        R = np.around(R, 4)
        DoS_occ = self.result['DoS_occ'][targ]
        # extrapolate to left-most boundary
        tmp = DoS_occ[:, 0] + (a[0] - a[1]) * (
            (DoS_occ[:, 1] - DoS_occ[:, 0]) / (a[2] - a[1]))
        DoS_occ = np.insert(DoS_occ, 0, tmp, axis=1)
        # extrapolate to right-most boundary
        tmp = DoS_occ[:, -1] + (a[-1] - a[-2]) * (
            (DoS_occ[:, -1] - DoS_occ[:, -2]) / (a[-2] - a[-3]))
        DoS_occ = np.insert(DoS_occ, -1, tmp, axis=1)
        # extrapolate to bottom-most boundary
        tmp = DoS_occ[0, :] + (R[0] - R[1]) * (
            (DoS_occ[1, :] - DoS_occ[0, :]) / (R[2] - R[1]))
        DoS_occ = np.insert(DoS_occ, 0, tmp, axis=0)
        # extrapolate to upper-most boundary
        tmp = DoS_occ[-1, :] + (R[-1] - R[-2]) * (
            (DoS_occ[-1, :] - DoS_occ[-2, :]) / (R[-2] - R[-3]))
        DoS_occ = np.insert(DoS_occ, -1, tmp, axis=0)
        DoS_occ = np.ma.masked_where(DoS_occ <= 0.0, DoS_occ)
        fig = plt.figure()
        ax = fig.add_subplot(111)
        cs = ax.contourf(a, R, DoS_occ, locator=ticker.LogLocator())
        cs2 = ax.contour(a, R, DoS_occ, levels=cs.levels[1:], colors='k')
        ax.set_xscale('log')
        ax.set_yscale('log')
        ax.set_xlabel('a (AU)')
        ax.set_ylabel('R ($R_\oplus$)')
        ax.set_title('Number of Planets - ' + name + ' (' +
                     str(self.result['NumObs'][targ]) + ')')
        cbar = fig.colorbar(cs)
        ax.clabel(cs2, fmt=ticker.LogFormatterMathtext(), colors='k')
        if path != None:
            fig.savefig(path,
                        format='pdf',
                        dpi=600,
                        bbox_inches='tight',
                        pad_inches=0.1)
        plt.show()
Ejemplo n.º 4
0
def plot(nmin=-2, nmax=1, tmin=0, tmax=2, num=301, B=5.4, npar=1.8):
    Taxis = scipy.logspace(tmin, tmax, num) * 1e-3
    naxis = scipy.logspace(nmin, nmax, num) * 1e20
    n, T = scipy.meshgrid(naxis, Taxis)
    om = scipy.pi * 2 * 4.6e9
    #wpe = n*pow(ec,2)/(e0*mes)
    print(nu(n, T))
    Ains = As(n, T, B, om, npar)
    Bins = Bs(n, T, B, om, npar)
    Cins = Cs(n, T, B, om, npar)

    Q = (-Bins + scipy.sqrt(pow(Bins, 2) - 4 * Ains * Cins)) / 2 / Ains
    output = scipy.sqrt(
        scipy.sqrt(pow(scipy.real(Q), 2) + pow(scipy.imag(Q), 2)) -
        scipy.real(Q)) / pow(2, .5)
    CS = plt.contour(naxis,
                     Taxis * 1e3,
                     om * output / 299792458.,
                     locator=ticker.LogLocator(),
                     linewidths=2.,
                     colors=colors['b'])  #om*output/299792458.
    plt.clabel(CS, inline=1, fontsize=16, fmt=ticker.LogFormatterMathtext())  #

    #CS2 = plt.contour(naxis,Taxis*1e3,pow(2,-1)*abs(scipy.imag(Q)/abs(scipy.sqrt(scipy.real(Q))))*om/299792458.,locator=ticker.LogLocator(),linewidths=2.,colors=colors['g'])#om*output/299792458.
    #plt.clabel(CS2, inline=1, fontsize=16,fmt=ticker.LogFormatterMathtext())#

    wpe = n * pow(ec, 2) / (e0 * mes)
    wce = ec * B / mes
    wci = ec * B / mi
    output2 = nu(n, T) * pow(wpe, .5) / (2 * pow(om, 2)) * scipy.sqrt(
        abs((npar**2 - 1) / (1 - wpe / (pow(wce, 2) * (npar**2 - 1)))))
    #CS3 = plt.contour(naxis,Taxis*1e3,output2*om/299792458.,locator=ticker.LogLocator(),linewidths=2.,colors=colors['r'])#om*output/299792458.

    output3 = nu(n, T) * pow(wpe, .5) / (2 * pow(om, 2)) * npar
    # CS2 = plt.contour(naxis,Taxis*1e3,output3*om/299792458.,locator=ticker.LogLocator(),linewidths=2.,colors=colors['g'])#om*output/299792458.
    #plt.clabel(CS2, inline=1, fontsize=16,fmt=ticker.LogFormatterMathtext())#

    #plt.clabel(CS3, inline=1, fontsize=16,fmt=ticker.LogFormatterMathtext())#

    A2 = pow(ec, 2) / (e0 * mi) / pow(om, 2)
    B2 = -2 * pow(e0 * mes, -.5) * ec / wce * npar
    C2 = npar**2 - 1

    temp = pow((-B2 - pow(B2**2 - 4 * A2 * C2, .5)) / (2 * A2), 2)
    plt.fill_between(naxis,
                     Taxis[0] * 1e3,
                     Taxis[-1] * 1e3,
                     naxis > temp,
                     color='k',
                     alpha=.3,
                     linewidth=2.)

    plt.gca().set_yscale("log")

    plt.gca().set_xscale("log")

    plt.ylabel(r'Electron Temperature [eV]')
    plt.xlabel(r'$n_e$ [m$^{-3}$]')

    plt.show()
Ejemplo n.º 5
0
    def GetMagneticFieldArea(self, X, Y, z, I, ax=None):
        B = np.zeros((len(X), len(Y)))

        for i, x in enumerate(X):
            for j, y in enumerate(Y):
                B[i, j] = self.GetMagneticField(
                    I,
                    [x, y, z],
                )

        if ax != None:
            YY, XX = np.meshgrid(Y, X)
            linthres = 10**(-15)  #abs(B).mean()
            vmax = 10**(-8)  #abs(B).max()
            norm = colors.SymLogNorm(linthresh=linthres, vmin=-vmax, vmax=vmax)

            im = ax[1].pcolormesh(XX, YY, B, cmap='RdBu_r', norm=norm)
            ax[1].scatter(self.Mol.Atom[:, 1], self.Mol.Atom[:, 2], color='k')
            tick_locations = ([-(10**x) for x in range(-15, 8, 1)][::-1] +
                              [0.0] + [(10**x) for x in range(-15, 8, 1)])
            cb = ax[0].colorbar(im,
                                ax=ax[1],
                                extend='both',
                                label='$Magnetic field$',
                                ticks=tick_locations,
                                format=ticker.LogFormatterMathtext())

#            cb.colorbar(ticks=tick_locations, format=ticker.LogFormatterMathtext())

        return B
Ejemplo n.º 6
0
def pcolormesh_symlog(ax,
                      X,
                      Y,
                      Z,
                      vmax=None,
                      vmin=None,
                      linthresh=None,
                      decades=4,
                      linscale=0.01,
                      cmap='RdBu_r',
                      cbar=True,
                      **kwargs):
    """Wrapper for matplotlib's pcolormesh that uses it sensibly, instead of the defaults.

    If linthresh is not specified, it defaults to vmax*10**(-decades), i.e. showing that number of decades each
    of positive and negative values.

    If not specified, vmax is set automatically
    In order to keep colors sensible, vmin is overridden unless set alone.
    """
    if vmax is None:
        if vmin is not None:
            vmax = -vmin
        else:
            vmax = np.abs(np.nanmax(Z)) * 2
            vmin = -vmax
            #print("Using automatic range {} to {}".format(vmin, vmax))
    else:
        vmin = -vmax

    int_min_pow, int_max_pow = int(np.ceil(np.log10(-vmin))), int(
        np.ceil(np.log10(vmax)))

    if linthresh is None:
        linthresh = vmax * 10**(-decades)

    logthresh = -int(np.ceil(np.log10(linthresh)))
    tick_locations = (
        [vmin] +
        [-(10.0**x) for x in range(int_min_pow - 1, -logthresh - 1, -1)] +
        [0.0] + [(10.0**x) for x in range(-logthresh, int_max_pow)] + [vmax])
    pcm = ax.pcolormesh(X,
                        Y,
                        Z,
                        norm=colors.SymLogNorm(linthresh=linthresh,
                                               linscale=linscale,
                                               base=10),
                        cmap=cmap,
                        vmin=-vmax,
                        vmax=vmax,
                        **kwargs)
    if cbar:
        # TODO add some more anonymous ticks
        plt.colorbar(pcm,
                     ax=ax,
                     ticks=tick_locations,
                     format=ticker.LogFormatterMathtext())

    return pcm
Ejemplo n.º 7
0
 def set_norm(self, value):
     self._cb.set_norm(value)
     if self.formatter is None:
         from matplotlib import colors, ticker
         if isinstance(value, colors.LogNorm):
             self._cb.formatter = ticker.LogFormatterMathtext()
         else:
             self._cb.formatter = ticker.ScalarFormatter()
Ejemplo n.º 8
0
def plot_photonB_vs_gamma(ax, root, step, sigma, gamma_c, emin=1e-2):
    fname = root + 'phst.tot.' + str(step).zfill(3)
    if not os.path.isfile(fname):
        data_gams = np.array([1e1])
        data_Bs = np.array([1e-3])
    else:
        data = h5py.File(fname, 'r')
        data_gams = data['gam'].value
        data_Bs = data['B'].value
    my_cmap = copy.copy(mpl.cm.get_cmap('jet'))
    my_cmap.set_bad(my_cmap(0))
    my_cmap.set_under(my_cmap(0))

    b_ax = np.linspace(-3,1,100)
    g_ax = np.linspace(0,4,100)
    if len(data_gams) > 10000:
        cnt = ax.hist2d(np.log10(data_gams), np.log10(data_Bs), bins=(g_ax, b_ax), norm=mpl.colors.LogNorm(), cmap=my_cmap);
    else:
        data_gams = np.array([1e1])
        data_Bs = np.array([1e-3])
        cnt = ax.hist2d(np.log10(data_gams), np.log10(data_Bs), bins=(g_ax, b_ax), norm=mpl.colors.LogNorm(vmin=1, vmax=1e5), cmap=my_cmap);
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="2%", pad=0.05)
    cbar = plt.colorbar(cnt[-1], cax = cax)
    cbar.set_label(r'\# of photons')

    g_ax, b_ax = np.meshgrid(g_ax, b_ax)
    epsph = (10**(g_ax) / gamma_c)**2 * 10**(b_ax) * np.sqrt(sigma / 1000.)
    levs = np.logspace(np.log10(emin), 3, (3-np.log10(emin)) + 1)
    clab = ax.contour(g_ax, b_ax, epsph, levels=levs, norm=mpl.colors.LogNorm(), colors='black');
    if len(levs > 5):
        clab = ax.contour(g_ax, b_ax, epsph, levels=levs[0::2], norm=mpl.colors.LogNorm(), colors='black');

    g_ticks = [0, 1, 2, 3, 4]
    ax.set_xticks(g_ticks)
    ax.set_xticklabels([r'$10^{{{0}}}$'.format(str(pow)) for pow in g_ticks])
    b_ticks = [-3, -2, -1, 0, 1]
    ax.set_yticks(b_ticks)
    ax.set_yticklabels([r'$10^{{{0}}}$'.format(str(pow)) for pow in b_ticks])

    fmt = ticker.LogFormatterMathtext()
    fmt.create_dummy_axis()

    clabs = ax.clabel(clab, fmt=fmt);

    [txt.set_bbox(dict(facecolor='white', edgecolor='black', pad=6)) for txt in clabs]

    ax.set_xlabel(r'particle $\gamma$')
    ax.set_ylabel(r'$B / B_{\rm up}$');
    ax.set_xlim(np.log10(5),np.log10(1e4))
    ax.set_ylim(-3,1)

    mpl.rcParams['hatch.color'] = (0,0,0,.2)
    xs = np.linspace(-1,4,5)
    ys = np.log10(emin * (1e3 / sigma)**0.5 * (gamma_c / 10**xs)**2)
    ax.fill_between(xs, -5, ys, hatch="//", linewidth=0.0, alpha=1.0, color='white')
    ax.fill_between(xs, -5, ys, hatch="//", linewidth=0.0, alpha=0.0)
Ejemplo n.º 9
0
 def __init__(
     self,
     ax,
     cmap=None,
     norm=None,
     alpha=None,
     values=None,
     boundaries=None,
     orientation='vertical',
     extend='neither',
     spacing='uniform',  # uniform or proportional
     ticks=None,
     format=None,
     drawedges=False,
     filled=True,
     extendfrac=None,
 ):
     self.ax = ax
     self._patch_ax()
     if cmap is None:
         cmap = cm.get_cmap()
     if norm is None:
         norm = colors.Normalize()
     self.alpha = alpha
     cm.ScalarMappable.__init__(self, cmap=cmap, norm=norm)
     self.values = values
     self.boundaries = boundaries
     self.extend = extend
     self._inside = self._slice_dict[extend]
     self.spacing = spacing
     self.orientation = orientation
     self.drawedges = drawedges
     self.filled = filled
     self.extendfrac = extendfrac
     self.solids = None
     self.lines = list()
     self.outline = None
     self.patch = None
     self.dividers = None
     self.set_label('')
     if cbook.iterable(ticks):
         self.locator = ticker.FixedLocator(ticks, nbins=len(ticks))
     else:
         self.locator = ticks  # Handle default in _ticker()
     if format is None:
         if isinstance(self.norm, colors.LogNorm):
             self.formatter = ticker.LogFormatterMathtext()
         else:
             self.formatter = ticker.ScalarFormatter()
     elif cbook.is_string_like(format):
         self.formatter = ticker.FormatStrFormatter(format)
     else:
         self.formatter = format  # Assume it is a Formatter
     # The rest is in a method so we can recalculate when clim changes.
     self.config_axis()
     self.draw_all()
Ejemplo n.º 10
0
def histogram_of_every_row(counts_col, **kwargs):
    """
    Plots the histogram of every row in a dataframe, overlaying them.
    Meant to be used within a map_dataframe call.

    Implementation inspired in https://matplotlib.org/gallery/api/histogram_path.html

    :param df: Dataframe
    :param counts_col: Name of the counts column
    :param edges_col: Name of the edges column
    :param ax: Matplotlib axis object
    :return:
    """
    ax = plt.gca()
    edges_col = kwargs.pop(
        "edges_col") if "edges_col" in kwargs else "hist_edges"
    data = kwargs.pop("data")
    color = kwargs.pop("color")
    label = kwargs.pop("label") if "label" in kwargs else None

    # FIXME: Find a way to increase opacity resolution
    min_op = 1. / 256.
    opacity = 1. / len(data)
    opacity = opacity if opacity >= min_op else min_op
    logger.info("plotting %d histograms overlaid with opacity %e." %
                (len(data), opacity))

    # get the corners of the rectangles for the histogram
    bins = data[edges_col].iloc[0]
    left = np.array(bins[:-1])
    right = np.array(bins[1:])
    bottom = np.zeros(len(left))

    for _ix, _d in data.iterrows():
        counts = _d[counts_col]
        top = bottom + counts

        # function to build a compound path
        XY = np.array([[left, left, right, right], [bottom, top, top,
                                                    bottom]]).T

        # get the Path object
        barpath = Path.make_compound_path_from_polys(XY)

        # make a patch out of it
        patch = PathPatch(barpath, alpha=opacity, lw=0, color=color)
        ax.add_patch(patch)

    ax.xaxis.set_major_locator(ticker.LogLocator(base=10))
    ax.xaxis.set_major_formatter(ticker.LogFormatterMathtext(base=10))
    ax.yaxis.set_major_formatter(EngFormatter(unit=''))
    ax.set_xlim(left[0], right[-1])
    ax.set_ylim(bottom.min(),
                data[counts_col].apply(lambda r: np.max(r)).max())
Ejemplo n.º 11
0
def CONTOUR_FLUX(ax, Om_Flux, D, L, r_start, r_end):
    Q, R = np.meshgrid(L, D)  #Curvas de nivel del flujo omnidireccional
    cs = plt.contour(Q, R, Om_Flux, locator=ticker.LogLocator(), Polar=True)
    #    manual_locations = [(0.05*np.pi, 6.5), (0*np.pi, 5.2), (0.05*np.pi,4.8),(0*np.pi, 4.2), (0.05*np.pi, 3.5), (-0.05*np.pi+np.pi, 6.5), (0*np.pi+np.pi, 5.2), (-0.05*np.pi+np.pi,4.8), (0*np.pi+np.pi, 4.2), (-0.05*np.pi+np.pi, 3.5)]
    #    manual_locations = [(0.05*np.pi, 3.5), (0*np.pi, 3.3), (-0.05*np.pi,3.1),(0.01*np.pi, 2.8), (0.05*np.pi, 2.1), (-0.05*np.pi+np.pi, 3.5), (0*np.pi+np.pi, 3.3), (0.05*np.pi+np.pi,3.1), (-0.01*np.pi+np.pi, 2.8), (-0.05*np.pi+np.pi, 2.1)]
    #    manual_locations = [(0*np.pi, 2.8), (0.04*np.pi, 2.5), (0*np.pi,2.1),(0.04*np.pi, 1.6), (0*np.pi+np.pi, 2.8), (-0.04*np.pi+np.pi, 2.5), (0*np.pi+np.pi,2.1), (-0.04*np.pi+np.pi, 1.6)]
    fmt = ticker.LogFormatterMathtext()
    labels = plt.clabel(cs, inline=1, fmt=fmt)
    # manual=manual_locations
    for l in labels:
        l.set_rotation(0)
Ejemplo n.º 12
0
def init():
    """initialize the TkAgg backend for gui
    and matplotlib figure with their axes (subplots) and visual settings.
    """
    use('TkAgg')  # matplotlib: set backend
    style.use('seaborn-whitegrid')

    XLIM_FFT = (1, FREQUENCY)
    YLIM_FFT = (0, REFRESH_TIME*FREQUENCY/2 + REFRESH_TIME*FREQUENCY/30)
    XLIM_SAMPLE = (0, FREQUENCY*REFRESH_TIME)
    YLIM_SAMPLE = (0, 3.3)  # 3.3V is signal max voltage

    global fig, sample_lines, fft_lines


    fig.subplots_adjust(bottom=0.15, top=0.92, hspace=.7)
    sample_graph = fig.add_subplot(2, 1, 1,
                                # TODO(low)show always REFRESH_TIME as max value
                                xlabel='samples in {} ms'.format(REFRESH_TIME),
                                ylabel='voltage',
                                xlim=XLIM_SAMPLE, ylim=YLIM_SAMPLE)
    sample_graph.set_title('time domain', fontsize=13)
    fft_graph = fig.add_subplot(2, 1, 2,
                                xlabel='frequency [Hz]', ylabel='FT magnitude',
                                xlim=XLIM_FFT, ylim=YLIM_FFT, xscale='log')
    fft_graph.set_title('frequency domain', fontsize=13)
    fft_graph.xaxis.grid(True, which='major', linewidth=0.7, color='0.5')
    fft_graph.xaxis.grid(which='minor', linestyle='-', color='0.5')
    fft_graph.yaxis.grid(which='major', color='0.7')
    subs = [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]  # ticks to show per decade
    fft_graph.xaxis.set_minor_locator(ticker.LogLocator(subs=subs))
    fft_graph.xaxis.set_major_formatter(ticker.LogFormatterMathtext(base=10.0,
                                        labelOnlyBase=False))

    sample_lines = sample_graph.plot([], [], 'g,', [], [], 'r.')
    fft_lines = fft_graph.plot([], [], 'g,', [], [], 'b-')
    # for settings check:
    # http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D
    # TIME: microphone1:
    # TODO check which one(if above is right)
    # sample_lines[0].set_linestyle('--')
    # TIME: microphone2:
    sample_lines[1].set_linestyle('-')
    sample_lines[1].set_linewidth(1)
    sample_lines[1].set_marker('')
    # sample_lines[1].set_markersize(0.1)
    # FREQ: microphone1:
    # FREQ: microphone2:
    fft_lines[1].set_linestyle('-')
    fft_lines[1].set_linewidth(1)
    fft_lines[1].set_marker('.')
    fft_lines[1].set_markersize(4)
    fft_lines[1].set_dash_capstyle('projecting')
    fft_lines[1].set_solid_capstyle('projecting')
Ejemplo n.º 13
0
def draw_faceted_heatmap(data, indexingdf, xaxis, yaxis, zaxis, lognorm,
                         cbarticks, logarithmic, symlog, symlognorm, linthresh,
                         **kwargs):
    originalColumnOrder = list(
        pd.unique(indexingdf.index.get_level_values(xaxis)))
    unsortedPivotedData = data.pivot_table(index=yaxis,
                                           columns=xaxis,
                                           values=zaxis)
    indexdf = indexingdf.groupby(level=yaxis, sort=False).first()
    data = reindexDataFrame(unsortedPivotedData, indexdf, False)
    data = data[originalColumnOrder]
    data.columns.name = xaxis
    plt.axis('off')
    if logarithmic:
        g = sns.heatmap(data,
                        norm=lognorm,
                        **kwargs,
                        cbar=True,
                        cbar_kws={
                            "ticks": cbarticks,
                            'label': zaxis
                        })
    elif symlog:
        linthresh = int(linthresh)
        maxlog = int(np.ceil(np.log10(data.values.max())))
        minlog = int(np.ceil(np.log10(-1 * data.values.min())))
        #tick_locations=([-(10**x) for x in range(-1*int(linthresh), minlog+1, 1)][::-1]+[0.0]+[(10**x) for x in range(-minlog,maxlog+1, 1)])
        tick_locations = ([-(10**x)
                           for x in range(-linthresh, minlog + 1, 1)][::-1] +
                          [0.0] + [(10**x)
                                   for x in range(-linthresh, maxlog + 1, 1)])
        #generate logarithmic ticks
        g = sns.heatmap(data,
                        norm=symlognorm,
                        cbar_kws={
                            'label': zaxis,
                            'ticks': tick_locations,
                            'format': ticker.LogFormatterMathtext()
                        },
                        **kwargs)
        #g = sns.heatmap(data, norm=symlognorm,**kwargs,cbar=True,cbar_kws={'label':zaxis})
    else:
        g = sns.heatmap(data, **kwargs, cbar=True, cbar_kws={'label': zaxis})

    #Add hiearchical level names and borders to heatmap
    ax1 = plt.gca()
    label_index(ax1, data)
    draw_borders(g, data)
    label_columns(ax1, data)

    label_headers(ax1, data)
Ejemplo n.º 14
0
def plot(r, z, t, xi, E, r_sim, xi_sim, SHM, track):

    fig, ax = plt.subplots()
    #Make color axis of electric field
    if SHM:
        colors = ax.pcolormesh(z, r, E, cmap="YlGnBu")
        cbar = fig.colorbar(colors, ax=ax)
        cbar.set_label('Electric Field ($m_e c\omega_p/e$)')
        ax.set_xlabel("z ($c/\omega_p$)")
        ax.set_ylabel("r ($c/\omega_p$)")
        ax.plot(xi, r, 'k')
    else:
        colors = ax.pcolormesh(xi_sim,
                               r_sim,
                               E,
                               norm=col.SymLogNorm(linthresh=0.03,
                                                   linscale=0.03,
                                                   vmin=-E.max(),
                                                   vmax=E.max()),
                               cmap="RdBu_r")

        tick_locations = [x * 0.01 for x in range(2, 10)] + [
            x * 0.01 for x in range(-10, -1)
        ] + [x * 0.1 for x in range(-10, 10)] + [x for x in range(-10, 10)]
        cbar = fig.colorbar(colors,
                            ax=ax,
                            ticks=tick_locations,
                            format=ticker.LogFormatterMathtext())
        cbar.set_label(
            '$E_r$, Transverse Electric Field ($m_e c\omega_p / e$)')
        ax.set_xlabel("$\\xi$ ($c/\omega_p$)")
        ax.set_ylabel('r ($c/\omega_p$)')
        ax.set_title('Electron trajectory from simulation v. OSIRIS for ' +
                     track + ' track')

        ax.plot(xi, r, 'k', label="Simulated")
    plt.plot(xi[-1], r[-1], 'ro', label="Simulated ($\\xi_f,r_f$)")
    plt.xlim(1.2, 1.5)  #xi_sim[0], xi_sim[-1])
    plt.ylim(0, 1)
    xi_OSIRIS, r_OSIRIS = plotSimTracks.get_xir(track)
    ax.plot(xi_OSIRIS, r_OSIRIS, 'c--', label="OSIRIS")
    plt.plot(xi_OSIRIS[-1], r_OSIRIS[-1], 'bo', label="OSIRIS ($\\xi_f,r_f$)")
    ax.legend()
    if SHM:
        model = "SHM"
    else:
        model = "simE"
    fn = "plots/" + model + "_" + track + ".png"
    plt.savefig(fn, dpi=200, transparent=True)
    plt.show()
Ejemplo n.º 15
0
class TestLogFormatterMathtext:
    fmt = mticker.LogFormatterMathtext()
    test_data = [
        (0, 1, '$\\mathdefault{10^{0}}$'),
        (0, 1e-2, '$\\mathdefault{10^{-2}}$'),
        (0, 1e2, '$\\mathdefault{10^{2}}$'),
        (3, 1, '$\\mathdefault{1}$'),
        (3, 1e-2, '$\\mathdefault{0.01}$'),
        (3, 1e2, '$\\mathdefault{100}$'),
        (3, 1e-3, '$\\mathdefault{10^{-3}}$'),
        (3, 1e3, '$\\mathdefault{10^{3}}$'),
    ]

    @pytest.mark.parametrize('min_exponent, value, expected', test_data)
    def test_min_exponent(self, min_exponent, value, expected):
        with mpl.rc_context({'axes.formatter.min_exponent': min_exponent}):
            assert self.fmt(value) == expected
Ejemplo n.º 16
0
def contour(ax, X, Y, Z, fill=True, contour_levels=10, line_levels=5, line_color='k', **kwargs):
    """
    Draw contour lines or filled contours.

    :param ax: Which axes to use for the plot.
    :param array X, Y: The coordinates of the values in Z. X and Y must both be 2-D with the same shape as Z (e.g. created via :py:func:`numpy.meshgrid`)
    :param array Z: 2D data to plot. 
    :param bool fill: draw contour lines or filled contours
    :param contour_levels: if fill is True; contour_levels determines the number of the filled contours.
    :param line_levels: if fill is True; line_levels determines the number of the lines.
    :param line_color: if fill is True; line_color determines the color of the lines.
    :param kwargs: Unknown keyword arguments are passed to :py:func:`ax.contour()` or :py:func:`ax.contourf()`.
    :return: image object

    >>> im = imshow(ax, X, Y, Z)
    Only draw contour lines.
    >>> im = contour(ax, x, y, Z, fill=True)
    Draw contour lines and filled contours,
    >>> im = contour(ax, x, y, Z, fill=True, contour_levels=10, line_levels=5)
    Draw contour lines and filled contours, filled levels determined by contour_levels and line number determined by line_levels
    >>> im = contour(ax, x, y, Z, fill=True, line_color='r')
    line color determined by line_color
    >>> im = contour(ax, x, y, Z, fill=True, cmap=plt.cm.bone)
    filled color determined by cmap
    >>> im = contour(ax, X, Y, Z, fill=True, alpha=0.5)
    The alpha blending value, between 0 (transparent) and 1 (opaque).
    >>> Zm = np.ma.masked_where(np.abs(Z) < 0.000001, Z)
    >>> im = contour(ax, x, y, Zm, fill=False)
    control the masked region.
    >>> from matplotlib import ticker
    >>> im = contour(ax, x, y, Z, locator=ticker.LogLocator(), fill=True)
    log locator tells contourf to use a log scale
    """
    assert X.shape == Z.shape and Y.shape == Z.shape, "The coordinates of X and Y must have the same shape as Z"
    if fill:
        line_factor = int(contour_levels)//int(line_levels)
        im = ax.contourf(X, Y, Z, levels=contour_levels, **kwargs)
        ax.contour(im, levels=im.levels[::line_factor], colors=line_color)
    else:
        im = ax.contour(X, Y, Z, locator=plt.LogLocator(), **kwargs)
        fmt = ticker.LogFormatterMathtext()
        ax.clabel(im, im.levels, fmt=fmt)
    return im
Ejemplo n.º 17
0
def plot_funct_with_Theta(a, b, x_size, y_size, theta):
    x_ax = np.linspace(-x_size,x_size);
    y_ax = np.linspace(-y_size,y_size);
    X,Y = np.meshgrid(x_ax,y_ax);

    himmelblau_fkt = (X**2 + Y -11)**2 + (X + Y**2 - 7)**2;

    fig, ax = plt.subplots();
    cs = ax.contour(X,Y,himmelblau_fkt, locator=plt.LogLocator());
    fmt = ticker.LogFormatterMathtext();
    fmt.create_dummy_axis();
    ax.clabel(cs, cs.levels, fmt=fmt);
    ax.set_title("Bananafunction Min at [1,1]");
    for a in range(theta[0].size - 1): #Plot all thetas inclusive the intermidiate results
        if(theta[0][a] != 0 or theta[1][a] != 0): #Only plot calculated values (instance created via np.zeros and probability for (0,0) is near zero...)
            plt.plot(theta[0][a],theta[1][a],'ro');
    #minima=[1 1];
    plt.plot(1,1,'rx');

    plt.show();
Ejemplo n.º 18
0
def plot_data_scalar(plot_ax,
                     slc,
                     ax_i,
                     field,
                     logscale=None,
                     override_lims=None,
                     cbar=True,
                     diverge_cmap=False,
                     override_cmap=None):
    slc_0, slc_1, field_dat = slc
    #diverge_cmap, logscale, zlim = True, False, (-30,30)
    #zlim = (-180,180)
    #if zlim is None: vmin, vmax = 1e-3, field_lims[field][1] #np.nanmax(field_dat), 1e-3
    #else: vmin, vmax = zlim

    if field in label_lookup: label = label_lookup[field]
    else: label = field

    norm, cmap, tick_locations, symlogscale = apply_scalar_lims(
        field, field_dat, override_lims=override_lims, logscale=logscale)
    if override_cmap is not None: cmap = override_cmap
    if field_dat.max() != field_dat.min():

        im = plot_ax.pcolormesh(slc_0.T,
                                slc_1.T,
                                np.ma.masked_array(field_dat.T),
                                norm=norm,
                                cmap=cmap,
                                rasterized=True)
        if cbar:
            if symlogscale:
                plt.colorbar(im,
                             ax=plot_ax,
                             label=label,
                             ticks=tick_locations,
                             format=ticker.LogFormatterMathtext())
            else:
                plt.colorbar(im, ax=plot_ax, label=label)

    plot_ax.set_xlim(slc_0.min(), slc_0.max())
    plot_ax.set_ylim(slc_1.min(), slc_1.max())
Ejemplo n.º 19
0
def plot_contour(df, vent=False, ax=None, values="MassArea", title="Isomass Plot", cmap='inferno', log=True, lines=True, line_cmap=None, line_colors=None, background="gradient", cbar_label=None,  save=None):

    # TODO: Figure out why low phi deposits break both the negative/grayscale linemaps, and the filled contours.  

    df = df[df[values]>0]

    piv = pd.pivot_table(df, index="Northing",
                         columns="Easting", values=values)

    if log:
        norm = LogNorm(vmin=piv.values.min(), vmax=piv.values.max())
    else:
        norm = None


    if ax is None:
        fig, ax = plt.subplots(1, 1)
    else:
        fig = plt.gcf()
    # ax.axis('equal')
    ax.set_ylabel("Northing")
    ax.set_xlabel("Easting")
    ax.set_title(title)

    if background == "gradient":
        if log:
            vals = np.log10(piv.values)
        else:
            vals = piv.values
        bg = ax.imshow(vals,
                       extent=[piv.columns.min(), piv.columns.max(),
                               piv.index.min(), piv.index.max()],
                       origin='lower',
                       cmap=cmap, alpha=1)
        if log:
            cbar = fig.colorbar(bg, ax=ax, format=r"$10^{%d}$")
        else:
            cbar = fig.colorbar(bg, ax=ax)
        cbar.set_alpha(alpha=1)
        cbar.draw_all()
        if cbar_label is not None:
            cbar.ax.set_ylabel(cbar_label, rotation=270)
    elif background == "fill":
        bg = ax.contourf(piv.columns, piv.index, piv.values,
                         cmap=cmap, vmin=piv.values.min(), vmax=piv.values.max())
        cbar = fig.colorbar(bg, ax=ax)
        cbar.set_alpha(alpha=1)
        cbar.draw_all()
        if cbar_label is not None:
            cbar.ax.set_ylabel(cbar_label, rotation=270)

    if lines:
        if line_cmap == "grayscale":
            colormap = cm.get_cmap(cmap, 256)
            oldcolors = colormap(np.linspace(0, 1, 256))
            newcolors = []
            for i, col in enumerate(oldcolors):
                r, g, b = [(1-col[j]) for j in range(3)]
                luminosity = 0.21*r + 0.72*g + 0.07*b
                newcolors.append([luminosity, luminosity, luminosity, 1])
            newcmp = ListedColormap(np.array(newcolors))
            lns = ax.contour(piv.columns, piv.index, piv.values, norm=norm,
                             cmap=newcmp)
        elif line_cmap == "negative":
            colormap = cm.get_cmap(cmap, 256)
            oldcolors = colormap(np.linspace(0, 1, 256))
            newcolors = [[(1-col[j]) for j in range(3)] + [1] for col in oldcolors]
            newcmp = ListedColormap(np.array(newcolors))
            lns = ax.contour(piv.columns, piv.index, piv.values, norm=norm,
                             cmap=newcmp)
        elif line_cmap is not None:
            lns = ax.contour(piv.columns, piv.index, piv.values, norm=norm,
                             cmap=line_cmap)
        elif line_colors is not None:
            lns = ax.contour(piv.columns, piv.index, piv.values, norm=norm,
                             colors=line_colors)
        else:
            lns = ax.contour(piv.columns, piv.index, piv.values, norm=norm,
                             colors='k')
        fmt = ticker.LogFormatterMathtext()
        fmt.create_dummy_axis()
        ax.clabel(lns, lns.levels, fmt=fmt, fontsize=10)



    if vent:
        ax.plot(vent[0], vent[1], 'r^', ms=8)

    ax.set_xlim(right=piv.columns.max(), left=piv.columns.min())
    ax.set_ylim(bottom=piv.index.min(), top=piv.index.max())
    ax.set_aspect("equal")

    return ax
Ejemplo n.º 20
0
    def graph_single_stat(self, means_df, ci_df, axis, **kwargs):
        all_means = self._rename_configs(self._reorder_configs(means_df))
        all_error = self._rename_configs(
            self._reorder_configs(ci_df)) if ci_df is not None else None
        all_perct = None
        labels = all_means.index.tolist()

        if self._kwargs_bool(kwargs, 'error_bars'):
            cutoff = self._kwargs_default(kwargs, 'cutoff',
                                          all_means.max().max())
            threshold = 0.01 * cutoff
            #print(all_error)
            all_error_clipped = all_error.clip(lower=threshold)
            are_equal = (all_error_clipped == all_error).all().all()
            if not are_equal:
                print('Setting error bar minimum to +/- {} for visibility'.
                      format(threshold))
                all_error = all_error_clipped
            if 'Average' in all_error.index:
                all_error.loc['Average'][:] = 0.0
            #print(all_error)
        elif all_error is not None:
            all_error[:] = 0
        else:
            all_error = all_means.copy()
            all_error[:] = 0.0

        num_configs = len(all_means.columns)
        width = num_configs / (num_configs + 2)
        bar_width = width / num_configs

        max_val = (all_means + all_error + 0.5).max().max()
        cutoff = self._kwargs_default(kwargs, 'cutoff', max_val)
        start = self._kwargs_default(kwargs, 'start', 0.0)
        axis.set_xlim(start, cutoff)
        axis.margins(0.0)

        ax = all_means.plot.barh(ax=axis,
                                 xerr=all_error,
                                 width=width,
                                 color='0.75',
                                 **self.barchart_defaults)

        text_df = all_means.T
        min_y_pos = 0.0
        max_y_pos = 0.0
        for i, bench in enumerate(text_df):
            for j, v in enumerate(reversed(text_df[bench])):
                offset = (j * bar_width) - (bar_width * (num_configs / 2)) + \
                        (bar_width / 2)
                y = i - offset
                min_y_pos = min(y - (bar_width / 2), min_y_pos)
                max_y_pos = max(y + (bar_width / 2), max_y_pos)
                precision = self._kwargs_default(kwargs, 'precision', 1)
                s = ('{0:.%df} ' % precision).format(v) if v >= cutoff or \
                        self._kwargs_bool(kwargs, 'add_numbers') else ''
                pos = cutoff if v >= cutoff else v
                if isnan(pos):
                    continue
                txt = ax.text(pos,
                              y,
                              s,
                              va='center',
                              ha='right',
                              color='white',
                              fontweight='bold',
                              fontfamily='sans',
                              fontsize=6)
                txt.set_path_effects(
                    [PathEffects.withStroke(linewidth=1, foreground='black')])

                if self._kwargs_bool(kwargs, 'label_bars'):
                    label_txt = ' ' + list(
                        reversed(text_df[bench].index.tolist()))[j]
                    txt2 = ax.text(0,
                                   y,
                                   label_txt,
                                   va='center',
                                   ha='left',
                                   color='white',
                                   fontweight='bold',
                                   fontfamily='sans',
                                   fontsize=6)
                    txt2.set_path_effects([
                        PathEffects.withStroke(linewidth=1, foreground='black')
                    ])

        ybounds = axis.get_ylim()
        if self._kwargs_bool(kwargs, 'flush'):
            axis.set_ylim(min_y_pos, max_y_pos)

        artist = []

        #labels = self._clean_benchmark_names(labels)

        ax.invert_yaxis()
        major_tick = max(float(int(cutoff / 10.0)), 1.0)
        if major_tick > 10.0:
            major_tick = 5.0 * int(major_tick / 5)
        ax.xaxis.set_major_locator(ticker.MultipleLocator(major_tick))
        if cutoff > 5.0:
            ax.xaxis.set_minor_locator(ticker.MultipleLocator(major_tick /
                                                              5.0))
        else:
            ax.xaxis.set_minor_locator(
                ticker.MultipleLocator(major_tick / 10.0))
        ax.set_axisbelow(True)

        bars = ax.patches

        num_configs = all_means.shape[1]
        num_bench = all_means.shape[0]
        hatches = (self.__class__.HATCH * 10)[:num_configs]
        all_hatches = sum(
            [list(itertools.repeat(h, num_bench)) for h in hatches], [])

        colors = [self._get_config_color(c) for c in all_means.columns]
        all_colors = sum(
            [list(itertools.repeat(c, num_bench)) for c in colors], [])

        for bar, hatch, color in zip(bars, all_hatches, all_colors):
            #bar.set_hatch(hatch)
            bar.set_color(color)
            bar.set_edgecolor('black')

        scale = self._kwargs_default(kwargs, 'scale', 1.0)
        if scale < 1.0:
            print('Scaling!')
            box = axis.get_position()
            new_box = [
                box.x0, box.y0 + box.height * (1.0 - scale), box.width,
                box.height * scale
            ]
            axis.set_position(new_box)

        plt.sca(axis)
        self.__class__._do_grid_lines()

        plt.xlabel(self._kwargs_default(kwargs, 'label', ''))
        plt.xscale(self._kwargs_default(kwargs, 'xscale', 'linear'))

        if 'xscale' in kwargs and 'symlog' in kwargs['xscale']:
            #locmin = ticker.LogLocator(base=10.0, subs=(0.1,0.2,0.4,0.6,0.8,1,2,4,6,8,10 ))
            locmin = ticker.NullLocator()
            ax.xaxis.set_minor_locator(locmin)
            ax.xaxis.set_minor_formatter(ticker.NullFormatter())
            #locmaj = ticker.LogLocator(base=100.0, subs=(1.0,), numdecs=0)
            locmaj = ticker.FixedLocator(
                locs=[1, 100, 10000, 1000000, 100000000])
            ax.xaxis.set_major_locator(locmaj)
            #ax.xaxis.set_major_formatter(ticker.FuncFormatter(
            #    lambda x, _: '%.0g' % (x) if x >= 0 else ''))
            ax.xaxis.set_major_formatter(ticker.LogFormatterMathtext())

        if self._kwargs_has(kwargs, 'tick_format'):
            ax.xaxis.set_major_formatter(
                FormatStrFormatter(kwargs['tick_format']))

        if self._kwargs_has(kwargs, 'legend'):
            legend = plt.legend(**kwargs['legend'])
            artist += [legend]
        else:
            plt.legend().set_visible(False)

        if self._kwargs_bool(kwargs, 'exclude_tick_labels'):
            plt.yticks(ticks=range(len(labels)), labels=[''] * len(labels))
        else:
            # plt.yticks(ticks=range(len(labels)), labels=labels, ha='right')

            minor_ticks = []
            if self._kwargs_has(kwargs, 'per_tick_label'):
                # Required to determine position of ticks.
                plt.gcf().canvas.draw()
                for tick in axis.yaxis.get_major_ticks():
                    tick_label = tick.label.get_text()
                    if tick_label not in kwargs['per_tick_label']:
                        continue

                    opt = kwargs['per_tick_label'][tick_label]

                    if 'font' in opt:
                        tick.label.set_fontproperties(
                            FontProperties(**opt['font']))

                    if self._kwargs_bool(opt, 'line_before'):
                        minor_ticks += [tick.get_loc() - 0.5]

            if len(minor_ticks):
                axis.yaxis.set_minor_locator(ticker.FixedLocator(minor_ticks))
                axis.tick_params(which='minor', axis='y', length=0, width=0)
                plt.grid(which='minor',
                         color='k',
                         linestyle='-',
                         axis='y',
                         zorder=5.0,
                         linewidth=2)

        return artist, ybounds
def heatmap(ax, arr, xrange, yrange, xy_label, label, log_norm=True, xy_label_force=None, less_xticks=False,
            skip_cbar=False, cbar_white_loc=1.0, **kwargs):
    """
    xrange: range of values for x
    yrange: range of y values
    fname: file saved as pdf and eps format with this name
    show: shows plots
    save: saves plot
    log_norm: heatmap is log, this is only used when plotting the posterior
    kwargs: a variety of keyword args are used below. They are mostly used for
    contour plot lines if I understand correctly. Using Duncan's default ones mostly,
    but we can talk about it.
    """
    # default parameters, this is relic ofthe previous way we did things. Still might be useful.
    if 'levels' in kwargs.keys(): levels = kwargs['levels']
    else: levels = [1E0] #, 1E5, 1E10, 1E20]

    if 'vmin' in kwargs.keys(): vmin = kwargs['vmin']
    else: vmin = 1E-3 #np.min(arr)

    if 'vmax' in kwargs.keys(): vmax = kwargs['vmax']
    else:
        if np.max(arr) > 1E10:
            vmax = 1E5
        else:
            vmax = 1E5 #np.max(arr)

    if 'contour_linestyle' in kwargs.keys(): contour_linestyle = kwargs['contour_linestyle']
    else: contour_linestyle = '-'

    if 'contour_color' in kwargs.keys(): contour_color = kwargs['contour_color']
    else: contour_color = 'k'

    if 'contour_linewidths' in kwargs.keys(): contour_lindewidths = kwargs['contour_linewidths']
    else: contour_lindewidths = 1.2

    if 'cmap_colour' in kwargs.keys(): cmap_colour = kwargs['cmap_colour']
    else: cmap_colour = 'RdBu_r'  #'YlGnBu' or 'RdBu_r'

    if 'fmt' in kwargs.keys(): fmt = kwargs['fmt']
    else: fmt = ticker.LogFormatterMathtext()

    if log_norm:
        arr = np.ma.array(arr, mask=( arr<=0.0 ) )
        if cmap_colour == 'RdBu_r':
            imshow_kw = {'cmap': cmap_colour, 'aspect': None, 'vmin': vmin, 'vmax': vmax, 'norm': MidPointLogNorm(vmin, vmax, cbar_white_loc)}
        else:
            imshow_kw = {'cmap': cmap_colour, 'aspect': None, 'vmin': vmin, 'vmax': vmax, 'norm': mpl.colors.LogNorm(vmin,vmax)}
        print("Logscale")
    else:
        imshow_kw = {'cmap': cmap_colour, 'aspect': None, 'vmin': vmin, 'vmax': vmax}

    # TODO change colour scheme, see https://matplotlib.org/examples/color/colormaps_reference.html
    # TODO fix ticks randomly disappearing on colourbar + flip colourbar minor ticks or remove?
    """
    Colours viridis, YlGnBu, terrain, plasma
    """

    im = ax.imshow(arr, interpolation='none', **imshow_kw)
    #im = plt.imshow(arr, interpolation='spline36', **imshow_kw)

    # axes setup

    # axes log scaled
    if less_xticks:
        ax.set_xticks([i for i, xval in enumerate(xrange) if (i % POINTS_BETWEEN_TICKS==0 and np.log10(xval)%2 == 0)])
        ax.set_xticklabels([r'$10^{%d}$' % np.log10(xval) for i, xval in enumerate(xrange) if (i % POINTS_BETWEEN_TICKS==0 and np.log10(xval)%2 == 0)], fontsize=FS)
    else:
        ax.set_xticks([i for i, cval in enumerate(xrange) if i % POINTS_BETWEEN_TICKS == 0])
        ax.set_xticklabels([r'$10^{%d}$' % np.log10(xval) for i, xval in enumerate(xrange) if (i % POINTS_BETWEEN_TICKS==0)], fontsize=FS)
    ax.set_yticks([i for i, kval in enumerate(yrange) if i % POINTS_BETWEEN_TICKS == 0])
    ax.set_yticklabels([r'$10^{%d}$' % np.log10(yval) for i, yval in enumerate(yrange) if i % POINTS_BETWEEN_TICKS==0], fontsize=FS)

    ax.invert_yaxis()
    ax.set_xlabel(xy_label[0], fontsize=FS); ax.set_ylabel(xy_label[1], fontsize=FS)

    # create colorbar
    #divider = make_axes_locatable(ax) # this does not work, proposed solution online for colorbar for multiplots
    #cax = divider.append_axes("right",size="5%",pad=0.05)
    #cbar = plt.colorbar(im, ax=cax)
    if skip_cbar:
        cbar = None
    else:
        cbar = plt.colorbar(im, ax=ax, fraction=0.046, pad=0.05) # Fig 3 way pad 0.04

        cbar.ax.set_ylabel(label, rotation=-90, va="bottom", fontsize=FS, labelpad=-20); cbar.ax.tick_params(labelsize=(FS), width=1,length=1)
        cbar.ax.minorticks_off();
        #cbar.set_ticks([round(vmin,3)+0.001,round(vmax,3)-0.001]) # UNCOMMENT THIS ONLY WHEN TICKS DON'T APPEAR
        cbar.update_ticks()


    # TODO IDK why do ticks hide sometimes?
    CL = ax.contour(arr, levels=levels, linestyles=contour_linestyle, colors=contour_color, linewidths=contour_lindewidths)
    ax.clabel(CL, CL.levels, inline=True, fmt=fmt, fontsize=FS-2)

    #Might be an issue
    #plt.tight_layout(h_pad=1)
    plt.tight_layout(h_pad=1,w_pad=1)

    return ax, cbar, im
Ejemplo n.º 22
0
    def _set_ticker(self, a):
        try:
            if not isiterable(self.ticks):
                if self.scale == 'linear':
                    a.set_major_locator(mticker.AutoLocator())
                elif self.scale == 'log':
                    a.set_major_locator(mticker.LogLocator(self.base))
                elif self.scale == 'symlog':
                    from matplotlib.scale import SymmetricalLogScale
                    if isMPL33:
                        scale = SymmetricalLogScale(
                            a,
                            base=self.base,
                            linthresh=self.symloglin,
                            linscale=self.symloglinscale)
                    else:
                        scale = SymmetricalLogScale(
                            a,
                            basex=self.base,
                            linthreshx=self.symloglin,
                            linscalex=self.symloglinscale)
                    a.set_major_locator(
                        mticker.SymmetricalLogLocator(scale.get_transform()))


#                    scale.set_default_locators_and_formatters(a)

                else:
                    a.set_major_locator(mticker.AutoLocator())
                #a.get_axes().locator_params(self.name[0], nbins = 10)
                if self.ticks is not None:
                    value = self.ticks
                else:
                    #figpage = a.get_axes().figobj.get_figpage()
                    figpage = a.axes.figobj.get_figpage()
                    if self.name[0] == 'x':
                        value = figpage.getp('nticks')[0]
                    elif self.name[0] == 'y':
                        value = figpage.getp('nticks')[1]
                    elif self.name[0] == 'z':
                        value = figpage.getp('nticks')[2]
                    else:
                        pass
                try:
                    # this works onlyfor MaxNLocator
                    #a.get_axes().locator_params(self.name[0], nbins = value)
                    a.axes.locator_params(self.name[0], nbins=value)
                except BaseException:
                    # for Symlog and LogLocator
                    a.get_major_locator().numticks = value
            else:
                a.set_ticks(self.ticks)

            if self.format == 'default':
                if self.scale == 'linear':
                    a.set_major_formatter(mticker.ScalarFormatter())
                elif self.scale == 'log':
                    a.set_major_formatter(
                        mticker.LogFormatterMathtext(self.base))
                elif self.scale == 'symlog':
                    a.set_major_formatter(
                        mticker.LogFormatterMathtext(self.base))
                else:
                    a.set_major_formatter(mticker.ScalarFormatter())
            elif self.format == 'scalar':
                a.set_major_formatter(mticker.ScalarFormatter())
            elif self.format == 'scalar(mathtext)':
                a.set_major_formatter(
                    mticker.ScalarFormatter(useOffset=True, useMathText=True))
                a.get_major_formatter().get_offset()
            elif self.format == 'log':
                a.set_major_formatter(mticker.LogFormatter(self.base))
            elif self.format == 'log(mathtext)':
                a.set_major_formatter(mticker.LogFormatterMathtext(self.base))
            elif self.format == 'log(exp)':
                a.set_major_formatter(mticker.LogFormatterExponent(self.base))
            elif self.format == 'none':
                a.set_major_formatter(mticker.NullFormatter())
            else:
                a.set_major_formatter(mticker.FormatStrFormatter(self.format))
        except BaseException:
            import traceback
            traceback.print_exc()
     fig = plt.figure()
     ax = fig.add_axes((0.2, 0.2, 0.7, 0.7))
 im = ax.pcolor(
     bn,
     bm,
     t_big,
     cmap="viridis_r",
     norm=LogNorm(vmin=tflat_big.min(), vmax=tflat_big.max()),
 )
 co = ax.contour(bn,
                 bm,
                 t_big,
                 levels=[1e14, 1e15],
                 colors="#FFFFFF",
                 linestyles="dashed")
 fmt = ti.LogFormatterMathtext()
 fmt.create_dummy_axis()
 plt.clabel(co, co.levels, fmt=fmt)
 #    sc = ax.scatter(
 #        nn,
 #        mm,
 #        c=residuals,
 #        cmap="RdBu_r",
 #        s=30,
 #        edgecolor="#444444",
 #        linewidth=0,
 #        norm=Normalize(
 #            vmin=-np.abs(residuals).max() * 1,
 #            vmax=np.abs(residuals).max() * 1,
 #        ),
 #    )
Ejemplo n.º 24
0
    def plot_contour(self,
                     values="MassArea",
                     vent=True,
                     title="Isomass Plot",
                     cmap='plasma',
                     log=True,
                     lines=True,
                     line_cmap=None,
                     line_colors='k',
                     background="gradient",
                     cbar_label=None,
                     save=None):

        piv = pd.pivot_table(self.df,
                             index="Northing",
                             columns="Easting",
                             values=values)
        if log:
            norm = LogNorm(vmin=piv.values.min(), vmax=piv.values.max())
            grad_values = np.log(piv.values)
        else:
            norm = None

        fig, ax = plt.subplots(1, 1)
        # ax.axis('equal')
        plt.ylabel("Northing")
        plt.xlabel("Easting")
        plt.title(title)

        if background == "gradient":
            bg = ax.imshow(np.log10(piv.values),
                           extent=[
                               piv.columns.min(),
                               piv.columns.max(),
                               piv.index.min(),
                               piv.index.max()
                           ],
                           origin='lower',
                           cmap=cmap,
                           alpha=0.7)
            if log:
                cbar = fig.colorbar(bg, ax=ax, format=r"$10^{%d}$")
            else:
                cbar = fig.colorbar(bg, ax=ax)
            cbar.set_alpha(alpha=0.5)
            cbar.draw_all()
            if cbar_label is not None:
                cbar.ax.set_ylabel(cbar_label, rotation=270)
        elif background == "fill":
            bg = ax.contourf(piv.columns,
                             piv.index,
                             piv.values,
                             norm=norm,
                             cmap=cmap)
            cbar = fig.colorbar(bg, ax=ax, extend='both')
            if cbar_label is not None:
                cbar.ax.set_ylabel(cbar_label, rotation=270)

        if lines:
            if line_cmap is not None:
                lns = ax.contour(piv.columns,
                                 piv.index,
                                 piv.values,
                                 norm=norm,
                                 cmap=lines_cmap)
            elif line_colors is not None:
                lns = ax.contour(piv.columns,
                                 piv.index,
                                 piv.values,
                                 norm=norm,
                                 colors=line_colors)

            fmt = ticker.LogFormatterMathtext()
            fmt.create_dummy_axis()
            ax.clabel(lns, lns.levels, fmt=fmt)

        if vent:
            plt.plot(self.vent.x, self.vent.y, 'r^', ms=8)

        plt.tight_layout()
        plt.gca().set_xlim(right=piv.columns.max(), left=piv.columns.min())
        plt.gca().set_ylim(bottom=piv.index.min(), top=piv.index.max())
        plt.gca().set_aspect("equal")
        if save is not None:
            plt.savefig(save, dpi=200, format='png')
        return fig, ax
Ejemplo n.º 25
0
def print_B_vs_alpha_safety():
    N = 500
    B = list(range(0, int(N/2), 1))
    C1 = [int((N - i)/2) for i in B]
    C2 = [N - B[i] - C1[i] for i in range(len(B))]
    k = 10
    alpha = list(range(int(k/2), k+1))
    zsafety = []
    zliveness = []
    cons = 20
    trials = 100
    for j in range(len(alpha)):
        # print(i)
        zssafety = []
        zsliveness = []
        for i in range(len(B)):    
            u = probOfStreak(trials, cons, hyper(N, B[i]+C1[i], k, alpha[j]))
            r_safety = (C1[i]**2)*(((1/(N-B[i]))*u)**2)
            v = 1 - probOfStreak(trials, cons, hyper(N, C1[i], k, alpha[j]))
            # r_safety = (len(C1)**2)*((probOfStreak(trials, cons, hyper(N, B[i]+C1[i], k, alpha[j])))**2)
            r_liveness = v
            # print("{},{},{}".format(B[i], C1[i], a), r)
            zssafety.append(r_safety)
            zsliveness.append(r_liveness)
            print(i, j, r_safety)                        
        zsafety.append(zssafety)
        zliveness.append(zsliveness)
    # fig = plt.figure()
    x, y = np.meshgrid(B, alpha)
    # max_z = max([max(i) for i in zsafety])
    # for i in range(len(zsafety)):
    #     for j in range(len(zsafety[i])):
    #         zsafety[i][j] /= max_z
    zsafety = np.array(zsafety)
    # max_z = max([max(i) for i in zliveness])
    # for i in range(len(zliveness)):
    #     for j in range(len(zliveness[i])):
    #         zliveness[i][j] /= max_z
    zliveness = np.array(zliveness)
    if True:
        fig, ax = plt.subplots(1, 1)
        pcm = ax.pcolor(x, y, zsafety, norm=colors.LogNorm(vmin=zsafety.min(), vmax=zsafety.max()),  cmap=cm.coolwarm)
        axim = ax.contour(x, y, zsafety, cmap=cm.Greys, norm = LogNorm())

        fmt = ticker.LogFormatterMathtext()
        fmt.create_dummy_axis()
        plt.clabel(axim, axim.levels, fmt=fmt)

        # CS = plt.contour(x, y, zsafety, norm=colors.LogNorm(vmin=zsafety.min(), vmax=zsafety.max()),  cmap=cm.binary)
        # fmt = ticker.LogFormatterMathtext()
        # fmt.create_dummy_axis()
        # plt.clabel(CS, CS.levels, fmt=fmt)
        # CS = plt.pcolor(x, y, zsafety, norm=colors.LogNorm(vmin=zsafety.min(), vmax=zsafety.max()),  cmap=cm.coolwarm)

        # plt.clabel(axim, axim.levels)
        fig.colorbar(pcm, ax=ax, extend='max')
        # ax = fig.add_subplot(111, projection='3d')
        # ax.plot_surface(x, y, zsafety, cmap=cm.coolwarm,linewidth=0, antialiased=False)
        # ax = fig.add_subplot(212, projection='3d')
        # ax.plot_surface(x, y, zliveness,linewidth=0, antialiased=False)
        # ax.set_zlim(10e-10, 1)
    else:
        # Plot liveness
        fig, ax = plt.subplots(1, 1)
        pcm = ax.pcolor(x, y, zliveness, cmap=cm.coolwarm)
        axim = ax.contour(x, y, zliveness, cmap=cm.Greys)
        fmt = ticker.LogFormatterMathtext()
        fmt.create_dummy_axis()
        plt.clabel(axim, axim.levels, fmt=fmt)
        fig.colorbar(pcm, ax=ax, extend='max')
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    plt.ylabel(r"$\alpha k,\ k=10$")
    plt.xlabel("Byzantine |$\mathcal{B}$| size, ($|\mathcal{N}| = 500$)")
    plt.show()
def __heatmap__(ax, arr, xrange, yrange, xy_label, label, log_norm=True, less_xticks=False,
                skip_cbar=False, cbar_white_loc=1.0, **kwargs):
    """
    xrange: range of values for x
    yrange: range of y values
    xy_label: list with first element the x label (str) and second element the
    y label (str)
    fname: file saved as pdf and eps format with this name
    show: shows plots
    save: saves plot
    log_norm: heatmap is log, this is only used when plotting the posterior
    kwargs: a variety of keyword args are used below. They are mostly used for
    contour plot lines
    """
    if 'levels' in kwargs.keys():
        levels = kwargs['levels']
    else:
        levels = [1E0]  # , 1E5, 1E10, 1E20]

    if 'vmin' in kwargs.keys():
        vmin = kwargs['vmin']
    else:
        vmin = 1E-3  # np.min(arr)

    if 'vmax' in kwargs.keys():
        vmax = kwargs['vmax']
    else:
        if np.max(arr) > 1E10:
            vmax = 1E5
        else:
            vmax = 1E5  # np.max(arr)

    if 'contour_linestyle' in kwargs.keys():
        contour_linestyle = kwargs['contour_linestyle']
    else:
        contour_linestyle = '-'

    if 'contour_color' in kwargs.keys():
        contour_color = kwargs['contour_color']
    else:
        contour_color = 'k'

    if 'contour_linewidths' in kwargs.keys():
        contour_lindewidths = kwargs['contour_linewidths']
    else:
        contour_lindewidths = 1.2

    if 'cmap_colour' in kwargs.keys():
        cmap_colour = kwargs['cmap_colour']
    else:
        cmap_colour = 'RdBu_r'  # 'YlGnBu' or 'RdBu_r'

    if 'fmt' in kwargs.keys():
        fmt = kwargs['fmt']
    else:
        fmt = ticker.LogFormatterMathtext()

    if log_norm:
        arr = np.ma.array(arr, mask=(arr <= 0.0))
        if cmap_colour == 'RdBu_r':
            imshow_kw = {'cmap': cmap_colour, 'aspect': None, 'vmin': vmin, 'vmax': vmax, 'norm': MidPointLogNorm(vmin, vmax, cbar_white_loc)}
        else:
            imshow_kw = {'cmap': cmap_colour, 'aspect': None, 'vmin': vmin, 'vmax': vmax, 'norm': mpl.colors.LogNorm(vmin, vmax)}
        print("Logscale")
    else:
        imshow_kw = {'cmap': cmap_colour, 'aspect': None, 'vmin': vmin, 'vmax': vmax}

    """
    Colours viridis, YlGnBu, terrain, plasma
    """

    im = ax.imshow(arr, interpolation='none', **imshow_kw)
    # im = plt.imshow(arr, interpolation='spline36', **imshow_kw)

    # axes setup

    # axes log scaled
    if less_xticks:
        ax.set_xticks([i for i, xval in enumerate(xrange) if (i % POINTS_BETWEEN_TICKS == 0 and np.log10(xval) % 2 == 0)])
        ax.set_xticklabels([r'$10^{%d}$' % np.log10(xval) for i, xval in enumerate(xrange) if (i % POINTS_BETWEEN_TICKS == 0 and np.log10(xval) % 2 == 0)], fontsize=FS)
    else:
        ax.set_xticks([i for i, cval in enumerate(xrange) if i % POINTS_BETWEEN_TICKS == 0])
        ax.set_xticklabels([r'$10^{%d}$' % np.log10(xval) for i, xval in enumerate(xrange) if (i % POINTS_BETWEEN_TICKS == 0)], fontsize=FS)
    ax.set_yticks([i for i, kval in enumerate(yrange) if i % POINTS_BETWEEN_TICKS == 0])
    ax.set_yticklabels([r'$10^{%d}$' % np.log10(yval) for i, yval in enumerate(yrange) if i % POINTS_BETWEEN_TICKS == 0], fontsize=FS)

    ax.invert_yaxis()
    ax.set_xlabel(xy_label[0], fontsize=FS)
    ax.set_ylabel(xy_label[1], fontsize=FS)

    # create colorbar
    if skip_cbar:
        cbar = None
    else:
        cbar = plt.colorbar(im, ax=ax, fraction=0.046, pad=0.05)  # Fig 3 way pad 0.04

        cbar.ax.set_ylabel(label, rotation=-90, va="bottom", fontsize=FS, labelpad=-20)
        cbar.ax.tick_params(labelsize=(FS), width=1, length=1)
        cbar.ax.minorticks_off()
        # cbar.set_ticks([round(vmin,3)+0.001,round(vmax,3)-0.001]) # UNCOMMENT THIS ONLY WHEN TICKS DON'T APPEAR
        cbar.update_ticks()

    CL = ax.contour(arr, levels=levels, linestyles=contour_linestyle, colors=contour_color, linewidths=contour_lindewidths)
    ax.clabel(CL, CL.levels, inline=True, fmt=fmt, fontsize=FS-2)

    plt.tight_layout(h_pad=1, w_pad=1)

    return ax, cbar, im
Ejemplo n.º 27
0
fmt = {}
strs = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']
for l, s in zip(CS1.levels, strs):
    fmt[l] = s

# Label every other level using strings
ax1.clabel(CS1, CS1.levels[::2], inline=True, fmt=fmt, fontsize=10)

###############################################################################
# Use a Formatter

fig2, ax2 = plt.subplots()

CS2 = ax2.contour(X, Y, 100**Z, locator=plt.LogLocator())
fmt = ticker.LogFormatterMathtext()
fmt.create_dummy_axis()
ax2.clabel(CS2, CS2.levels, fmt=fmt)
ax2.set_title("$100^Z$")

plt.show()

#############################################################################
#
# .. admonition:: References
#
#    The use of the following functions, methods, classes and modules is shown
#    in this example:
#
#    - `matplotlib.axes.Axes.contour` / `matplotlib.pyplot.contour`
#    - `matplotlib.axes.Axes.clabel` / `matplotlib.pyplot.clabel`
def main(graph_name):

    G = nx.read_gml(graph_name)
    #    G = nx.connected_component_subgraphs(G)[0] ### For plotting Giant component ###
    top_nodes = []
    top_nodes.append(G.nodes())
    topn = map(int, G.nodes())
    string_mapping = dict(zip(G.nodes(), map(int, G.nodes())))

    G = nx.relabel_nodes(G, string_mapping)

    H = nx.DiGraph(
    )  #### For undirected graph use H = nx.Graph() and for directed use nx.DiGraph()
    H.add_edges_from(G.edges())
    #    print G.edges()
    activity = []
    #    nodepos = []
    pos = nx.graphviz_layout(H, prog='neato', args='')
    #    pos = nx.spring_layout(H,iterations=100)
    for n in topn:
        nodelabel = G.node[n]['label']
        activity.append(
            float(G.node[n]['activity']) / float(G.node[n]['time_in_system']))
#        nodepos.append(int(nodelabel))
    max_activity = max(activity)
    min_activity = min(activity)
    #    print activity
    pop_plus = []
    pop_minus = []
    pop_zero = []
    pop = []
    size_plus = []
    size_minus = []
    size_zero = []
    nodepos_plus = []
    nodepos_minus = []
    nodepos_zero = []

    for n in topn:
        pop.append(
            ((float(G.node[n]['activity']) /
              float(G.node[n]['time_in_system'])) / np.log(float(max_activity))
             ))  ### One can change it to log scale too !!!
        size_node = 100 * (float(G.node[n]['n_weight_change']))
        if size_node > 0:
            size_plus.append(size_node)
            nodepos_plus.append(int(G.node[n]['id']))
            pop_plus.append(((float(G.node[n]['activity']) /
                              float(G.node[n]['time_in_system'])) /
                             np.log(float(max_activity))))

        if size_node < 0:
            size_minus.append(abs(size_node))
            nodepos_minus.append(int(G.node[n]['id']))
            pop_minus.append(((float(G.node[n]['activity']) /
                               float(G.node[n]['time_in_system'])) /
                              np.log(float(max_activity))))

        if size_node == 0:
            size_zero.append(abs(size_node))
            nodepos_zero.append(int(G.node[n]['id']))
            pop_zero.append(((float(G.node[n]['activity']) /
                              float(G.node[n]['time_in_system'])) /
                             np.log(float(max_activity))))


#    print size_minus, size_plupop_minuss
    print pop_zero, pop_minus, pop_plus

    colors_plus = []
    for rank_plus in pop_plus:
        colors_plus.append(plot.cm.jet(float(rank_plus)))

    colors_minus = []
    for rank_minus in pop_minus:
        colors_minus.append(plot.cm.jet(float(rank_minus)))

    colors_zero = []
    for rank_zero in pop_zero:
        colors_zero.append(plot.cm.jet(float(rank_zero)))

    fig = plot.figure(figsize=(11, 11))
    ax = fig.add_axes((0.0, 0.0, 1.0, 1.0))

    #    cax = ax.imshow([activity],cmap=cm.jet,norm=LogNorm(vmin=min_activity, vmax=max_activity))

    #    cax = ax.imshow([activity],cmap=cm.jet)
    #    nx.draw(H,pos,node_color=colors,node_shape='o',node_size = size_minus, with_labels=False)

    #    nx1.draw_networkx_nodes(H,pos,nodelist=None,node_size = 300, node_shape = 'o', node_color=colors, cmap=plot.cm.jet)

    nx.draw_networkx_nodes(H,
                           pos,
                           nodelist=nodepos_plus,
                           node_size=size_plus,
                           node_shape='s',
                           node_color=colors_plus,
                           cmap=plot.cm.jet)

    nx.draw_networkx_nodes(H,
                           pos,
                           nodelist=nodepos_minus,
                           node_size=size_minus,
                           node_shape='o',
                           node_color=colors_minus,
                           cmap=plot.cm.jet)

    nx.draw_networkx_nodes(H,
                           pos,
                           nodelist=nodepos_zero,
                           node_size=size_minus,
                           node_shape='o',
                           node_color=colors_zero,
                           cmap=plot.cm.jet)

    nx2.draw_networkx_edges(H,
                            pos,
                            edgelist=None,
                            edge_color='k',
                            style='solid',
                            alpha=0.25)

    #    nx1.draw_networkx_labels(H,pos,labels=None,font_size=10) ### For labeling the nodes with uid

    formatter = ticker.LogFormatterMathtext()
    #colorbar(format=formatter)

    plot.rcParams["font.size"] = 12
    #    c=plot.colorbar(cax,orientation='vertical',shrink = 0.55,format=formatter)

    #    c.set_label("Normalized Total Activity of Users")
    #    pyplot.title('weight-loss (circle) and weight-gain (square)')
    pyplot.axis('off')
    pyplot.show()
Ejemplo n.º 29
0
def create_plot(field,
                xy,
                fdat,
                r,
                show=False,
                fname='Output/test.pdf',
                override_lims=None):
    if override_lims is None:
        override_lims = {}

    # Check to see if the field diverges
    if field in field_lims_shells:
        vmin, vmax = field_lims_shells[field]
        #linthresh = 10**(int(np.ceil(np.log10(vmax)))-4.5)
        linthresh = 1e4

    if field in override_lims:
        vmin, vmax = override_lims[field]

    if sum([1 for k in diverging_field_keys if k in field]):
        cmap = 'RdBu'
        fdat = np.ma.filled(np.ma.masked_invalid(fdat), 0)
        if field not in field_lims_shells:
            vmax = np.max(np.abs(fdat))
            vmin = -1 * vmax
            if len(fdat[fdat > 0]) == 0: return
            linthresh = 100 * np.min(np.abs(fdat[fdat > 0]))
    else:
        cmap = 'viridis'
        #fdat = np.ma.masked_where(fdat==0, fdat)
        fdat = np.ma.masked_invalid(fdat)
        if field not in field_lims_shells:
            vmin, vmax = np.min(fdat), np.max(fdat)

    symlog = False
    if sum([1 for k in symlog_field_keys if k in field]):
        norm = SymLogNorm(vmin=vmin, vmax=vmax, linthresh=linthresh)
        maxlog = int(np.ceil(np.log10(vmax)))
        minlog = int(np.ceil(np.log10(-vmin)))
        linlog = int(np.ceil(np.log10(linthresh)))
        symlog = True

        #generate logarithmic ticks
        tick_locations = ([-(10**x) for x in range(minlog, linlog - 1, -1)] +
                          [0.0] + [(10**x) for x in range(linlog, maxlog + 1)])
    elif sum([1 for k in log_field_keys if k in field]):
        norm = LogNorm(vmin=vmin, vmax=vmax)
    else:
        norm = Normalize(vmin=vmin, vmax=vmax)

    lon, lat = xy
    plt.pcolormesh(lon,
                   lat,
                   fdat.reshape(lon.shape),
                   cmap=cmap,
                   norm=norm,
                   rasterized=True,
                   vmin=vmin,
                   vmax=vmax)
    if symlog:
        plt.colorbar(label=label_lookup[field],
                     ticks=tick_locations,
                     format=ticker.LogFormatterMathtext())
    else:
        if field in label_lookup:
            plt.colorbar(label=label_lookup[field])
        else:
            plt.colorbar(label=field)

    plt.gca().set_aspect('equal')

    plt.ylim(-90, 90)
    plt.xlim(-90, 270)
    plt.xticks([-90, -30, 30, 90, 150, 210, 270])
    plt.yticks([-90, -45, 0, 45, 90])
    plt.xlabel('Longitude (0=Dayside, 180=Nightside)')
    plt.ylabel('Latitude')
    plt.title('R = {0} (RM)'.format(r))
    print('Saving: {0}'.format(fname))
    if show:
        plt.show()
    else:
        plt.savefig(fname)
    plt.close()
def __heatmap2__(arr, crange, koffrange, fname, label, show=SHOW, save=True, log_norm=True, log_norm_axes_only=False,
                 dedim=False, xy_label_force=None, less_xticks=True, return_cb=False, **kwargs):
    """
    crange: range of values for c
    koffrange: range of koff values
    fname: file saved as pdf and eps format with this name
    show: shows plots
    save: saves plots
    log_norm: heatmap is log, this is only used when plotting the posterior
    dedim: makes the axis dedimensionalized. scales them (see by how much below)
    kwargs: a variety of keyword args are used below. They are mostly used for contour plot lines
    """
    # default parameters
    if 'levels' in kwargs.keys():
        levels = kwargs['levels']
    else:
        levels = [1E0, 1E1, 1E2, 1E3]

    if 'vmin' in kwargs.keys():
        vmin = kwargs['vmin']
    else:
        vmin = np.min(arr)

    if 'vmax' in kwargs.keys():
        vmax = kwargs['vmax']
    else:
        vmax = np.max(arr)

    if 'contour_linestyle' in kwargs.keys():
        contour_linestyle = kwargs['contour_linestyle']
    else:
        contour_linestyle = '-'

    if 'contour_color' in kwargs.keys():
        contour_color = kwargs['contour_color']
    else:
        contour_color = 'k'

    if 'contour_linewidths' in kwargs.keys():
        contour_lindewidths = kwargs['contour_linewidths']
    else:
        contour_lindewidths = 2

    if 'cmap_colour' in kwargs.keys():
        cmap_colour = kwargs['cmap_colour']
    else:
        cmap_colour = 'YlGnBu'

    if 'fmt' in kwargs.keys():
        fmt = kwargs['fmt']
    else:
        fmt = ticker.LogFormatterMathtext()

    if 'fig_width' in kwargs.keys():
        fig_width = kwargs['fig_width']
    else:
        fig_width = 3.0

    if dedim:
        # if flag is true, this is how we scale the axis. Simple.
        crange = crange*KON/KP
        koffrange = koffrange/KP
        xy_label = [r'$k_{on}c/k_{p}$', r'$k_{off}/k_{p}$']
    else:
        xy_label = [r'${c}$', r'${k}_{off}$']
    if xy_label_force is not None:
        xy_label = xy_label_force

    # we want most of the functionality that comes with log_norm, but not the log colorbar
    if log_norm and not log_norm_axes_only:
        imshow_kw = {'cmap': cmap_colour, 'aspect': None, 'vmin': vmin, 'vmax': vmax, 'norm': mpl.colors.LogNorm(vmin, vmax)}
    else:
        imshow_kw = {'cmap': cmap_colour, 'aspect': None, 'vmin': vmin, 'vmax': vmax}

    """
    Colours viridis, YlGnBu, terrain, plasma
    """
    # plot setup
    f = plt.figure(figsize=(fig_width, fig_width/1.2))
    im = plt.imshow(arr, interpolation='spline36', **imshow_kw)

    # axes setup
    fig = plt.gcf()
    ax = plt.gca()

    # axes log scaled
    if less_xticks:
        ax.set_xticks([i for i, cval in enumerate(crange) if (i % POINTS_BETWEEN_TICKS == 0 and np.log10(cval) % 2 == 0)])
        ax.set_xticklabels([r'$10^{%d}$' % np.log10(cval) for i, cval in enumerate(crange) if (i % POINTS_BETWEEN_TICKS == 0 and np.log10(cval) % 2 == 0)], fontsize=FS)
    else:
        ax.set_xticks([i for i, cval in enumerate(crange) if i % POINTS_BETWEEN_TICKS == 0])
        ax.set_xticklabels([r'$10^{%d}$' % np.log10(cval) for i, cval in enumerate(crange) if (i % POINTS_BETWEEN_TICKS == 0)], fontsize=FS)
    ax.set_yticks([i for i, kval in enumerate(koffrange) if i % POINTS_BETWEEN_TICKS == 0])
    ax.set_yticklabels([r'$10^{%d}$' % np.log10(yval) for i, yval in enumerate(koffrange) if i % POINTS_BETWEEN_TICKS == 0], fontsize=FS)

    ax.invert_yaxis()
    ax.set_xlabel(xy_label[0], fontsize=FS)
    ax.set_ylabel(xy_label[1], fontsize=FS)

    # create colorbar
    cbar = fig.colorbar(im, fraction=0.0375, pad=0.04)
    cbar.ax.set_ylabel(label, rotation=-90, va="bottom", fontsize=FS, labelpad=5)
    cbar.ax.tick_params(labelsize=FS)
    cbar.ax.minorticks_off()
    # UNCOMMENT THIS ONLY WHEN TICKS DON'T APPEAR
    # cbar.set_ticks([round(vmin,3)+0.001,round(vmax,3)-0.001])
    cbar.update_ticks()
    cbar.ax.minorticks_off()

    CL = plt.contour(arr, levels=levels, linestyles=contour_linestyle, colors=contour_color, linewidths=contour_lindewidths)
    plt.clabel(CL, CL.levels, inline=True, fmt=fmt)

    # now we can set the ticks without them getting messed up
    if not log_norm:
        ax = plt.gca()
        ax.set_xticks([i for i, cval in enumerate(crange) if i % POINTS_BETWEEN_TICKS == 0] + [len(crange)])
        ax.set_yticks([i for i, kval in enumerate(koffrange) if i % POINTS_BETWEEN_TICKS == 0] + [len(koffrange)])

        # Exhausting process to make ticks look nice
        nice_ticks = ["{}".format(cval) for cval in crange if Decimal(str(cval)) % Decimal(str(crange[-1] / 5)) == 0]
        ctilde_ticks = []
        for i in range(len(nice_ticks) * 2):
            if i % 2 == 0:
                ctilde_ticks.append("")
            else:
                ctilde_ticks.append(nice_ticks.pop(0))
        ctilde_ticks = ["0"] + ctilde_ticks

        nice_ticks = ["{}".format(koffval) for koffval in koffrange if
                      Decimal(str(koffval)) % Decimal(str(koffrange[-1] / 5)) == 0]
        kofftilde_ticks = []
        for i in range(len(nice_ticks) * 2):
            if i % 2 == 0:
                kofftilde_ticks.append("")
            else:
                kofftilde_ticks.append(nice_ticks.pop(0))
        kofftilde_ticks = ["0"] + kofftilde_ticks

        ax.set_xticklabels(ctilde_ticks, fontsize=FS)
        ax.set_yticklabels(kofftilde_ticks, fontsize=FS)

    # save
    if save:
        plt.savefig(DIR_OUTPUT + os.sep + fname + '.pdf')
        plt.savefig(DIR_OUTPUT + os.sep + fname + '.eps')
        plt.savefig(DIR_OUTPUT + os.sep + fname + '.png')
    if show:
        plt.show()

    plt.close()
    if return_cb:
        return fig, ax, cbar
    else:
        return fig, ax