Exemplo n.º 1
1
def test_zooming_with_inverted_axes():
    fig, ax = plt.subplots()
    ax.plot([1, 2, 3], [1, 2, 3])
    ax.axis([1, 3, 1, 3])
    inset_ax = zoomed_inset_axes(ax, zoom=2.5, loc='lower right')
    inset_ax.axis([1.1, 1.4, 1.1, 1.4])

    fig, ax = plt.subplots()
    ax.plot([1, 2, 3], [1, 2, 3])
    ax.axis([3, 1, 3, 1])
    inset_ax = zoomed_inset_axes(ax, zoom=2.5, loc='lower right')
    inset_ax.axis([1.4, 1.1, 1.4, 1.1])
Exemplo n.º 2
0
def plot_us(lats, lons, save_name=None):
    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111)
    big_map = Basemap(resolution='h',
                      lat_0=36, lon_0=-107.5,
                      llcrnrlat=32, llcrnrlon=-125,
                      urcrnrlat=43, urcrnrlon=-110)
    big_map.drawcoastlines()
    big_map.drawstates()
    big_map.drawcountries()
    big_map.drawmapboundary(fill_color='#7777ff')
    big_map.fillcontinents(color='#ddaa66', lake_color='#7777ff', zorder=0)
    x, y = big_map(lons, lats)
    big_map.plot(x[0], y[0], 'ro', markersize=2)

    axins = zoomed_inset_axes(ax, 20, loc=1)
    ll_lat, ll_lon = 37.8, -122.78
    ur_lat, ur_lon = 38.08, -122.43

    axins.set_xlim(ll_lon, ur_lon)
    axins.set_ylim(ur_lon, ur_lat)

    small_map = Basemap(resolution='h',
                        llcrnrlat=ll_lat, llcrnrlon=ll_lon,
                        urcrnrlat=ur_lat, urcrnrlon=ur_lon,
                        ax=axins)
    small_map.drawcoastlines()
    small_map.drawmapboundary(fill_color='#7777ff')
    small_map.fillcontinents(color='#ddaa66', lake_color='#7777ff', zorder=0)
    x, y = small_map(lons, lats)
    small_map.plot(x, y, 'ro', markersize=3)

    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
    if save_name: 
        fig.savefig(save_name)
Exemplo n.º 3
0
def render_input_spectrum():

    folder = "/cosma/home/durham/rhgk18/ls_structure/pks"
    bao    = folder+"/wig.txt"
    nbao   = folder+"/nowig.txt"

    pkbao  = np.loadtxt(bao)
    pknbao = np.loadtxt(nbao)

    fig, ax = plt.subplots()

    ax.loglog(pkbao[:,0]  ,pkbao[:,1]  , color='r', label='With BAO')
    ax.loglog(pknbao[:,0] ,pknbao[:,1] , color='b', label='Without BAO')
    ax.set_xlabel("Wavenumber, $k$ [$h/Mpc$]", size=28)
    ax.set_ylabel("Power, $P(k)$ [$(Mpc/h)^3$]", size=28)
    ax.legend(prop={'size':28})
    
    axins = zoomed_inset_axes(ax, 5, loc=3)
    axins.loglog(pkbao[:,0]  ,pkbao[:,1]  , color='r', label='iWith BAO')
    axins.loglog(pknbao[:,0] ,pknbao[:,1] , color='b', label='iWithout BAO')

    x1, x2, y1, y2 = 0.02, 0.1, 5000, 30000
    axins.set_xlim(x1, x2)
    axins.set_ylim(y1, y2)

    plt.xticks(visible=False)
    plt.yticks(visible=False)

    mark_inset(ax, axins, loc1=2, loc2=1, fc="none", ec="0.5")

    
    plt.show()
def setup_axes02(fig, rect, zoom=0.35, loc=4, axes_class=None, axes_kwargs=None):
    """
    ax2 is an inset axes, but shares the x- and y-axis with ax1.
    """

    from mpl_toolkits.axes_grid1.axes_grid import ImageGrid, CbarAxes
    import mpl_toolkits.axes_grid1.inset_locator as inset_locator

    grid = ImageGrid(fig, rect,
                     nrows_ncols=(1,1),
                     share_all=True, aspect=True,
                     label_mode='L', cbar_mode="each",
                     cbar_location='top', cbar_pad=None, cbar_size='5%',
                     axes_class=(axes_class, axes_kwargs))

    ax1 = grid[0]

    kwargs = dict(zoom=zoom, loc=loc)
    ax2 = inset_locator.zoomed_inset_axes(ax1,
                                          axes_class=axes_class,
                                          axes_kwargs=axes_kwargs,
                                          **kwargs
                                          )


    cax = inset_locator.inset_axes(ax2, "100%", 0.05, loc=3,
                                   borderpad=0.,
                                   bbox_to_anchor=(0, 0, 1, 0),
                                   bbox_transform=ax2.transAxes,
                                   axes_class=CbarAxes,
                                   axes_kwargs=dict(orientation="top"),
                                   )

    ax2.cax = cax
    return grid[0], ax2
Exemplo n.º 5
0
def plot_target_pred(train_xdata, test_xdata, train_ydata, test_ydata, loc=5):
    maxval = max(train_xdata.max(), test_xdata.max(), train_ydata.max(), test_ydata.max())
    minval = min(train_xdata.min(), test_xdata.min(), train_ydata.min(), test_ydata.min())

    fig, ax = plt.subplots()
    ax.plot(train_xdata, train_ydata, '.', label="Train")
    ax.plot(test_xdata, test_ydata, '.', label="Test")
    plt.legend(loc="best")
    ax.plot([minval, maxval], [minval, maxval], '--')
    plt.xlabel("Target Value (kcal/mol)")
    plt.ylabel("Predicted Value (kcal/mol)")

    axins = zoomed_inset_axes(ax, 30, loc=loc) # 30 is zoom, loc is .... nuts
    axins.plot(train_xdata, train_ydata, '.', label="Train")
    axins.plot(test_xdata, test_ydata, '.', label="Test")
    axins.plot([minval, maxval], [minval, maxval], '--')
    # sub region of the original image
    middle = test_xdata.mean() - 170
    x1, x2, y1, y2 = -15+middle, 15+middle, -15+middle, 15+middle
    axins.set_xlim(x1, x2)
    axins.set_ylim(y1, y2)

    mark_inset(ax, axins, loc1=2, loc2=3, fc="none", ec="0.5")
    plt.draw()
    plt.show()
Exemplo n.º 6
0
    def inset_momentum_axes(cd):

        # TODO: This plot does not refresh correctly, skip the inset
        fig = mpl.figure(cd.plotfigure.figno)
        axes = fig.add_subplot(111)

        # Plot main figure
        axes.plot(cd.x, hu_1(cd), 'b-')
        axes.plot(cd.x, hu_2(cd), 'k--')
        axes.set_xlim(xlimits)
        axes.set_ylim(ylimits_momentum)
        momentum_axes(cd)

        # Create inset plot
        from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
        from mpl_toolkits.axes_grid1.inset_locator import mark_inset
        inset_axes = zoomed_inset_axes(axes, 0.5, loc=3)
        inset_axes.plot(cd.x, hu_1(cd), 'b-')
        inset_axes.plot(cd.x, hu_2(cd), 'k--')
        inset_axes.set_xticklabels([])
        inset_axes.set_yticklabels([])
        x_zoom = [-120e3,-30e3]
        y_zoom = [-10,10]
        inset_axes.set_xlim(x_zoom)
        inset_axes.set_ylim(y_zoom)
        mark_inset(axes, inset_axes, loc1=2, loc2=4, fc='none', ec="0.5")
        # mpl.ion()
        mpl.draw()
Exemplo n.º 7
0
def plot_linear_kernel_pairs(pairs):
    xdata, ydata = zip(*pairs)
    maxval = max(max(xdata), max(ydata))

    fig, ax = plt.subplots()
    ax.plot(xdata, ydata, '.')
    ax.plot([0, maxval], [0, maxval], '--')
    plt.xlabel("Linear Ridge Mean Absolute Error (kcal/mol)")
    plt.ylabel("Kernel Ridge Mean Absolute Error (kcal/mol)")

    # 15 is the zoom, loc is nuts
    axins = zoomed_inset_axes(ax, 15, loc=5)
    axins.plot(xdata, ydata, '.')
    axins.plot([0, maxval], [0, maxval], '--')

    # sub region of the original image
    axins.set_xlim(1, 6)
    axins.set_ylim(1, 6)

    # draw a bbox of the region of the inset axes in the parent axes and
    # connecting lines between the bbox and the inset axes area
    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

    plt.draw()
    plt.show()
    def create_inset_axes(self):
        ax_inset = zoomed_inset_axes(self.ax, 2, loc=1)

        cm = plt.get_cmap('winter')
        ax_inset.set_color_cycle([cm(1.*i/self.num_graphs)
                                 for i in range(self.num_graphs)])

        # hide every other tick label
        for label in ax_inset.get_xticklabels()[::4]:
            label.set_visible(False)

        return ax_inset
Exemplo n.º 9
0
def test_gettightbbox():
    fig, ax = plt.subplots(figsize=(8, 6))

    l, = ax.plot([1, 2, 3], [0, 1, 0])

    ax_zoom = zoomed_inset_axes(ax, 4)
    ax_zoom.plot([1, 2, 3], [0, 1, 0])

    mark_inset(ax, ax_zoom, loc1=1, loc2=3, fc="none", ec='0.3')

    remove_ticks_and_titles(fig)
    bbox = fig.get_tightbbox(fig.canvas.get_renderer())
    np.testing.assert_array_almost_equal(bbox.extents,
                                         [-17.7, -13.9, 7.2, 5.4])
Exemplo n.º 10
0
def makeplot(refl, winds, w, stride, map, gs, title, file_name, box=None):
    pylab.figure()
    axmain = pylab.axes((0, 0.025, 1, 0.9))

    gs_x, gs_y = gs
    nx, ny = refl.shape
    xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny))

    pylab.contourf(xs, ys, refl, levels=np.arange(10, 80, 10))
    pylab.colorbar()
    pylab.contour(xs, ys, w, levels=np.arange(-10, 0, 2), colors='#666666', style='--')
    pylab.contour(xs, ys, w, levels=np.arange(2, 12, 2), colors='#666666', style='-')
    
    u, v = winds
    wind_slice = tuple([ slice(None, None, stride) ] * 2)
    pylab.quiver(xs[wind_slice], ys[wind_slice], u[wind_slice], v[wind_slice])

    if box:
        lb_y, lb_x = [ b.start for b in box ]
        ub_y, ub_x = [ b.stop for b in box ]

        box_xs = gs_x * np.array([ lb_x, lb_x, ub_x, ub_x, lb_x])
        box_ys = gs_y * np.array([ lb_y, ub_y, ub_y, lb_y, lb_y])

        map.plot(box_xs, box_ys, '#660099')

        axins = zoomed_inset_axes(pylab.gca(), 4, loc=4)
        pylab.sca(axins)

        pylab.contourf(xs[box], ys[box], refl[box], levels=np.arange(10, 80, 10))
        pylab.contour(xs[box], ys[box], w[box], levels=np.arange(-10, 0, 2), colors='#666666', style='--')
        pylab.contour(xs[box], ys[box], w[box], levels=np.arange(2, 12, 2), colors='#666666', style='-')
        pylab.quiver(xs[box], ys[box], u[box], v[box])

        drawPolitical(map)

        pylab.xlim([lb_x * gs_x, ub_x * gs_x - 1])
        pylab.ylim([lb_y * gs_y, ub_y * gs_y - 1])

        mark_inset(axmain, axins, loc1=1, loc2=3, fc='none', ec='k')

    pylab.sca(axmain)
    drawPolitical(map)

    pylab.suptitle(title)
    pylab.savefig(file_name)
    pylab.close()
    return
Exemplo n.º 11
0
def plotConfusion(confusion, grid, title, file_name, inset=None, fudge=16):
    pylab.figure()
    axmain = pylab.axes()

    tick_labels = [ "Missing", "Correct\nNegative", "False\nAlarm", "Miss", "Hit" ]
    min_label = -1

    xs, ys = grid.getXY()

    pylab.pcolormesh(xs, ys, confusion, cmap=confusion_cmap, vmin=min_label, vmax=(min_label + len(tick_labels) - 1))

    tick_locs = np.linspace(-1, min_label + len(tick_labels) - 2, len(tick_labels))
    tick_locs += (tick_locs[1] - tick_locs[0]) / 2
    bar = pylab.colorbar()
    bar.locator = FixedLocator(tick_locs)
    bar.formatter = FixedFormatter(tick_labels)
    pylab.setp(pylab.getp(bar.ax, 'ymajorticklabels'), fontsize='large')
    bar.update_ticks()

    grid.drawPolitical()

    if inset:
        lb_y, lb_x = [ b.start for b in inset ]
        ub_y, ub_x = [ b.stop + fudge for b in inset ]

        inset_exp = (slice(lb_y, ub_y), slice(lb_x, ub_x))

        axins = zoomed_inset_axes(pylab.gca(), 2, loc=4)
        pylab.sca(axins)

        pylab.pcolormesh(xs[inset_exp], ys[inset_exp], confusion[inset_exp], cmap=confusion_cmap, vmin=min_label, vmax=(min_label + len(tick_labels) - 1))
        grid.drawPolitical()

        gs_x, gs_y = grid.getGridSpacing()

        pylab.xlim([lb_x * gs_x, (ub_x - 1) * gs_x])
        pylab.ylim([lb_y * gs_y, (ub_y - 1) * gs_y])

        mark_inset(axmain, axins, loc1=1, loc2=3, fc='none', ec='k')

    pylab.sca(axmain)
    pylab.suptitle(title)
    pylab.savefig(file_name)
    pylab.close()
    return
Exemplo n.º 12
0
def test_inset_locator():
    def get_demo_image():
        from matplotlib.cbook import get_sample_data
        import numpy as np
        f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
        z = np.load(f)
        # z is a numpy array of 15x15
        return z, (-3, 4, -4, 3)

    fig, ax = plt.subplots(figsize=[5, 4])

    # prepare the demo image
    Z, extent = get_demo_image()
    Z2 = np.zeros([150, 150], dtype="d")
    ny, nx = Z.shape
    Z2[30:30 + ny, 30:30 + nx] = Z

    # extent = [-3, 4, -4, 3]
    ax.imshow(Z2, extent=extent, interpolation="nearest",
              origin="lower")

    axins = zoomed_inset_axes(ax, zoom=6, loc='upper right')
    axins.imshow(Z2, extent=extent, interpolation="nearest",
                 origin="lower")
    axins.yaxis.get_major_locator().set_params(nbins=7)
    axins.xaxis.get_major_locator().set_params(nbins=7)
    # sub region of the original image
    x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
    axins.set_xlim(x1, x2)
    axins.set_ylim(y1, y2)

    plt.xticks(visible=False)
    plt.yticks(visible=False)

    # draw a bbox of the region of the inset axes in the parent axes and
    # connecting lines between the bbox and the inset axes area
    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

    asb = AnchoredSizeBar(ax.transData,
                          0.5,
                          '0.5',
                          loc='lower center',
                          pad=0.1, borderpad=0.5, sep=5,
                          frameon=False)
    ax.add_artist(asb)
Exemplo n.º 13
0
def draw_inset(plt, m, pos, lat, lon):
    ax = plt.subplot(111)
    zoom = 50
    axins = zoomed_inset_axes(ax, zoom, loc=1)
    m.plot(lon, lat, '.b--', zorder=10, latlon=True)
    m.scatter(lon, lat,  # longitude first!
              latlon=True,  # lat and long in degrees
              zorder=11)  # on top of all
    x1, y1 = m(lon[1] - 0.005, lat[0] - 0.0025)
    x2, y2 = m(lon[1] + 0.005, lat[0] + 0.0025)
    axins.set_xlim(x1, x2)
    axins.set_ylim(y1, y2)

    plt.xticks(visible=False)
    plt.yticks(visible=False)
    # draw a bbox of the region of the inset axes in the parent axes and
    # connecting lines between the bbox and the inset axes area
    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
def plot_calibration(c, insert = True):
    fig = plt.figure()
    ax = plt.gca()
    for baseline, correlation in c.time_domain_correlations_values.items():
        correlation_max_val = correlation[np.argmax(correlation)]
        correlation_max_time = c.time_domain_correlations_times[baseline][np.argmax(correlation)]
        lines = ax.plot(
            c.time_domain_correlations_times[baseline] * 1e9,
            correlation / correlation_max_val,
            label = baseline)
        #ax.plot([correlation_max_time, correlation_max_time], [0, correlation_max_val], color = lines[0].get_color())
    ax.set_ylim(top=1.2)
    ax.xaxis.set_ticks(np.arange(
        -200,
        200,
        2))
    if insert == True:
        #axins = zoomed_inset_axes(ax, 5, loc=1)
        axins = zoomed_inset_axes(ax, 9, loc=1)
        for baseline, correlation in c.time_domain_correlations_values.items():
            correlation_max_val = correlation[np.argmax(correlation)]
            correlation_max_time = c.time_domain_correlations_times[baseline][np.argmax(correlation)]
            lines = axins.plot(
                c.time_domain_correlations_times[baseline] * 1e9,
                correlation / correlation_max_val,
                label = baseline,
                linewidth=2)
            #axins.plot([correlation_max_time, correlation_max_time], [0, correlation_max_val], color = lines[0].get_color())
        #axins.set_xlim(-0.4, 2.9)
        axins.set_xlim(-0.4, 0.4)
        #axins.set_ylim(0.90, 1.04)
        axins.set_ylim(0.96, 1.03)
        #axins.xaxis.set_ticks(np.arange(-0.4, 2.9, 0.4))
        axins.xaxis.set_ticks(np.arange(-0.4, 0.4, 0.2))
        mark_inset(ax, axins, loc1=2, loc2=3, fc='none', ec='0.5')

    plt.xticks(visible=True)
    plt.yticks(visible=False)
    ax.set_title("Time domain cross correlations with broad band noise\n arriving through full RF chain AFTER calibration")
    ax.set_xlabel("Time delay (ns)")
    ax.set_ylabel("Cross correlation value (normalised)")
    ax.legend(loc=2)
    #ax.legend()
    plt.show()
Exemplo n.º 15
0
def plot_site(options):
    options['prefix'] = 'site'
    fig = MyFig(options, figsize=(10, 8), legend=True, grid=False, xlabel=r'Probability $p_s$', ylabel=r'Reachability~$\reachability$', aspect='auto')
    fig_vs = MyFig(options, figsize=(10, 8), legend=True, grid=False, xlabel=r'Fraction of Forwarded Packets~$\forwarded$', ylabel=r'Reachability~$\reachability$', aspect='auto')

    if options['grayscale']:
        colors = options['graycm'](pylab.linspace(0, 1.0, 3))
    else:
        colors = fu_colormap()(pylab.linspace(0, 1.0, 3))
    nodes = 105

    axins = None
    if options['inset_loc'] >= 0:
        axins = zoomed_inset_axes(fig_vs.ax, options['inset_zoom'], loc=options['inset_loc'])
        axins.set_xlim(options['inset_xlim'])
        axins.set_ylim(options['inset_ylim'])
        axins.set_xticklabels([])
        axins.set_yticklabels([])
        mark_inset(fig_vs.ax, axins, loc1=2, loc2=3, fc="none", ec="0.5")

    for i, (name, label) in enumerate(names):
        data = parse_site_only(options['datapath'][0], name)
        rs = numpy.array([r for p, r, std, conf, n, fw, fw_std, fw_conf in data if r <= options['limit']])
        fws = numpy.array([fw for p, r, std, conf, n, fw, fw_std, fw_conf in data if r <= options['limit']])/(nodes-1)
        ps = numpy.array([p for p, r, std, conf, n, fw, fw_std, fw_conf in data]) #[0:len(rs)])
        yerr = numpy.array([conf for p,r,std,conf, n, fw, fw_std, fw_conf in data]) #[0:len(rs)])

        patch_collection = PatchCollection([conf2poly(ps, list(rs+yerr), list(rs-yerr), color=colors[i])], match_original=True)
        patch_collection.set_alpha(0.3)
        patch_collection.set_linestyle('dashed')
        fig.ax.add_collection(patch_collection)

        fig.ax.plot(ps, rs, label=label, color=colors[i])
        fig_vs.ax.plot(fws, rs, label=label, color=colors[i])
        if axins:
            axins.plot(fws, rs, color=colors[i])

    fig.ax.set_ylim(0, options['limit'])
    fig.legend_title = 'Graph'
    fig.save('graphs')
    fig_vs.legend_title = 'Graph'
    fig_vs.ax.set_xlim(0,1)
    fig_vs.ax.set_ylim(0,1)
    fig_vs.save('vs_pb')
Exemplo n.º 16
0
def pltimg(imname,loca,xl,xh,yh,yl,descrip):
    ## Main image
    ax=subplot(3,3,loca);
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    ax.text(0.5,0.1,descrip,transform=ax.transAxes,color="white",weight='bold',horizontalalignment='center',fontsize=8)
    ax.imshow(imname,cmap="YlOrBr_r");
    axins=zoomed_inset_axes(ax,2,loc=1)
    axins.imshow(imname,cmap="YlOrBr_r");
    
    ## Inset
    x1, x2, y1, y2 = xl,xh,yh,yl
    axins.set_xlim(x1, x2)
    axins.set_ylim(y1, y2)
    axins.xaxis.set_visible(False)
    axins.yaxis.set_visible(False)
    axins.spines['bottom'].set_color('white')
    axins.spines['top'].set_color('white')
    axins.spines['left'].set_color('white')
    axins.spines['right'].set_color('white')
Exemplo n.º 17
0
def zoomed_axis(ax=plt.gca(),xlim=[None,None],ylim=[None,None],
                remove_ticks=True,zoom=1,borderpad=1,loc=4,**kw):
    """
    Creates a (pretty) zoomed axis
    
    Args:
        ax: which axis to zoom on
        <x/y>_lim: the axes limits
        remove_ticks: if true, removes the x and y ticks, to reduce clutter
        remaining args: passed to zoomed_inset_axes
    Returns:
        the inset axis
    """    
    axins = zoomed_inset_axes(ax, zoom=zoom, loc=loc,borderpad=borderpad)
    axins.set_xlim(*xlim) # apply the x-limits
    axins.set_ylim(*ylim) # apply the y-limits
    if (remove_ticks):
        PlotUtilities.no_x_anything(axins)
        PlotUtilities.no_y_anything(axins)
    return axins
def setup_inset_axes(parent_axes, f_hst, **kwargs):
    import mpl_toolkits.axes_grid1.inset_locator as inset_locator

    if "zoom" not in kwargs:
        kwargs["zoom"] = 4
    if "loc" not in kwargs:
        kwargs["loc"] = 1

    gh3 = pywcsgrid2.GridHelper(wcs=f_hst[0].header)

    axes_class = pywcsgrid2.Axes
    axes_kwargs=dict(grid_helper=gh3)

    ax3 = inset_locator.zoomed_inset_axes(parent_axes,
                                          axes_class=axes_class,
                                          axes_kwargs=axes_kwargs,
                                          **kwargs
                                          )

    ax3.axis[:].toggle(all=False)

    return ax3
Exemplo n.º 19
0
def test_fill_facecolor():
    fig, ax = plt.subplots(1, 5)
    fig.set_size_inches(5, 5)
    for i in range(1, 4):
        ax[i].yaxis.set_visible(False)
    ax[4].yaxis.tick_right()
    bbox = Bbox.from_extents(0, 0.4, 1, 0.6)

    # fill with blue by setting 'fc' field
    bbox1 = TransformedBbox(bbox, ax[0].transData)
    bbox2 = TransformedBbox(bbox, ax[1].transData)
    # set color to BboxConnectorPatch
    p = BboxConnectorPatch(
        bbox1, bbox2, loc1a=1, loc2a=2, loc1b=4, loc2b=3,
        ec="r", fc="b")
    p.set_clip_on(False)
    ax[0].add_patch(p)
    # set color to marked area
    axins = zoomed_inset_axes(ax[0], 1, loc='upper right')
    axins.set_xlim(0, 0.2)
    axins.set_ylim(0, 0.2)
    plt.gca().axes.get_xaxis().set_ticks([])
    plt.gca().axes.get_yaxis().set_ticks([])
    mark_inset(ax[0], axins, loc1=2, loc2=4, fc="b", ec="0.5")

    # fill with yellow by setting 'facecolor' field
    bbox3 = TransformedBbox(bbox, ax[1].transData)
    bbox4 = TransformedBbox(bbox, ax[2].transData)
    # set color to BboxConnectorPatch
    p = BboxConnectorPatch(
        bbox3, bbox4, loc1a=1, loc2a=2, loc1b=4, loc2b=3,
        ec="r", facecolor="y")
    p.set_clip_on(False)
    ax[1].add_patch(p)
    # set color to marked area
    axins = zoomed_inset_axes(ax[1], 1, loc='upper right')
    axins.set_xlim(0, 0.2)
    axins.set_ylim(0, 0.2)
    plt.gca().axes.get_xaxis().set_ticks([])
    plt.gca().axes.get_yaxis().set_ticks([])
    mark_inset(ax[1], axins, loc1=2, loc2=4, facecolor="y", ec="0.5")

    # fill with green by setting 'color' field
    bbox5 = TransformedBbox(bbox, ax[2].transData)
    bbox6 = TransformedBbox(bbox, ax[3].transData)
    # set color to BboxConnectorPatch
    p = BboxConnectorPatch(
        bbox5, bbox6, loc1a=1, loc2a=2, loc1b=4, loc2b=3,
        ec="r", color="g")
    p.set_clip_on(False)
    ax[2].add_patch(p)
    # set color to marked area
    axins = zoomed_inset_axes(ax[2], 1, loc='upper right')
    axins.set_xlim(0, 0.2)
    axins.set_ylim(0, 0.2)
    plt.gca().axes.get_xaxis().set_ticks([])
    plt.gca().axes.get_yaxis().set_ticks([])
    mark_inset(ax[2], axins, loc1=2, loc2=4, color="g", ec="0.5")

    # fill with green but color won't show if set fill to False
    bbox7 = TransformedBbox(bbox, ax[3].transData)
    bbox8 = TransformedBbox(bbox, ax[4].transData)
    # BboxConnectorPatch won't show green
    p = BboxConnectorPatch(
        bbox7, bbox8, loc1a=1, loc2a=2, loc1b=4, loc2b=3,
        ec="r", fc="g", fill=False)
    p.set_clip_on(False)
    ax[3].add_patch(p)
    # marked area won't show green
    axins = zoomed_inset_axes(ax[3], 1, loc='upper right')
    axins.set_xlim(0, 0.2)
    axins.set_ylim(0, 0.2)
    axins.get_xaxis().set_ticks([])
    axins.get_yaxis().set_ticks([])
    mark_inset(ax[3], axins, loc1=2, loc2=4, fc="g", ec="0.5", fill=False)
Exemplo n.º 20
0
axesb.set_xlabel("$Number$ $of$ $EG's$", fontsize=40)
axesb.xaxis.set_tick_params(labelsize=20)
axesb.xaxis.set_major_formatter(mtick.FormatStrFormatter("%1.e"))
axesb.yaxis.set_tick_params(labelsize=20)
axesb.yaxis.set_major_formatter(mtick.FormatStrFormatter("%1.e"))
###

##########################################
for i in nhj.keys():

    axesb.plot(nhjb[i][1], nhja[i][1], ".", markersize=1.0)


from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes

axins = zoomed_inset_axes(axesb, 3.0, loc=4)

for i in nhj.keys():

    axins.plot(nhjb[i][1], nhja[i][1], "o", markersize=4.0)

x1, x2, y1, y2 = 350, 470, 900, 1100  # specify the limits
axins.set_xlim(x1, x2)  # apply the x-limits
axins.set_ylim(y1, y2)  # apply the y-limits
plt.yticks(visible=False)
plt.xticks(visible=False)
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

mark_inset(axesb, axins, loc1=1, loc2=2, fc="none", ec="0.0")

##############################################
Exemplo n.º 21
0
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
def add_sizebar(ax, size):
   asb =  AnchoredSizeBar(ax.transData,
                         size,
                         str(size),
                         loc=8,
                         pad=0.1, borderpad=0.5, sep=5,
                         frameon=False)
   ax.add_artist(asb)
fig = plt.figure(1, [5.5, 3])
ax = fig.add_subplot(1,2,1)
ax.set_aspect(1.)
axins = inset_axes(ax,
                   width="30%", # width = 30% of parent_bbox
                   height=1., # height : 1 inch
                   loc=3)
plt.xticks(visible=False)
plt.yticks(visible=False)
ax = fig.add_subplot(1,2,2)
ax.set_aspect(1.)
axins = zoomed_inset_axes(ax, 0.5, loc=1) # zoom = 0.5
plt.xticks(visible=False)
plt.yticks(visible=False)
add_sizebar(ax, 0.5)
add_sizebar(axins, 0.5)
plt.draw()
plt.show()
    correlation_time_upped *= 1e9
    fig = plt.figure()
    ax1 = fig.gca()
    ax1.plot(correlation_time_upped, correlation_upped, color='b', linewidth=2, label="Upsampled")
    ax1.plot(correlation_time, correlation, color='r', linewidth=2, marker='.', markersize=15, label="Raw")
    xy_before = (correlation_time[np.argmax(correlation)-1], correlation[np.argmax(correlation)-1])
    ax1.annotate('higher', xy=xy_before,
                xytext=(0.2, 0.4), textcoords='axes fraction',
                arrowprops=dict(facecolor='black', shrink=0.09, width=2),
                horizontalalignment='right', verticalalignment='top',)
    xy_after = (correlation_time[np.argmax(correlation)+1], correlation[np.argmax(correlation)+1])
    ax1.annotate('lower', xy=xy_after,
                xytext=(0.6, 0.3), textcoords='axes fraction',
                arrowprops=dict(facecolor='black', shrink=0.09, width=2),
                horizontalalignment='right', verticalalignment='top',)
    axins = zoomed_inset_axes(ax1, 9, loc=1)
    axins.plot(correlation_time_upped, correlation_upped, color='b', marker='.', linewidth=2, label="Upsampled")
    axins.plot(correlation_time, correlation, color='r', linewidth=2, marker='.', markersize=15, label="Raw")

    axins.set_xlim(-3.2, -2.2)
    axins.set_ylim(0.97, 1.05)
    axins.xaxis.set_ticks(np.arange(-3.4, -1.9, 0.4))
    #plt.xticks(visible=False)
    plt.yticks(visible=False)
    mark_inset(ax1, axins, loc1=2, loc2=3, fc='none', ec='0.5')

    ax1.set_title("Comparison of raw time domain cross correlation with upsampled version")
    ax1.set_xlabel("Time shift (ns)")
    ax1.set_ylabel("Cross correlation value (normalised)")
    ax1.legend(loc=2)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3,4,-4,3)


fig = plt.figure(1, [5,4])
ax = fig.add_subplot(111)

Z, extent = get_demo_image()

ax.set(aspect=1,
       xlim=(-15, 15),
       ylim=(-20, 5))


axins = zoomed_inset_axes(ax, 2, loc=2) # zoom = 6
im = axins.imshow(Z, extent=extent, interpolation="nearest",
                  origin="lower")

plt.xticks(visible=False)
plt.yticks(visible=False)


# colorbar
cax = inset_axes(axins,
                 width="5%", # width = 10% of parent_bbox width
                 height="100%", # height : 50%
                 loc=3,
                 bbox_to_anchor=(1.05, 0., 1, 1),
                 bbox_transform=axins.transAxes,
                 borderpad=0,
Exemplo n.º 24
0
    def plotmustarsigma(self, outputid = 0, zoomperc = 0.05, loc = 2):
        '''
        Plot the mu* vs sigma chart to interpret the combined effect of both.
        

        Parameters
        -----------
        zoomperc : float (0-1)
            the percentage of the output range to show in the zoomplot,
            if 'none', no zoom plot is added
        loc : int
            matplotlib.pyplot.legend: location code (0-10)
        outputid : int
            the output to use whe multiple are compared; starts with 0

        Returns
        ---------
        fig : matplotlib.figure.Figure object
            figure containing the output
        ax1 : axes.AxesSubplot object
            the subplot
        txtobjects : list of textobjects
            enbales the ad hoc replacement of labels when overlapping

        Notes
        -------
        Visualization as proposed by [M2]_
        '''

        mustar2use = self.mustar[outputid*self._ndim:(outputid+1)*self._ndim]
        sigma2use = self.sigma[outputid*self._ndim:(outputid+1)*self._ndim]

        fig = plt.figure()
        ax1 = fig.add_subplot(111)
        axs, txtobjects = scatterwithtext(ax1, mustar2use, sigma2use,
                                          self._namelist, 'ks', markersize = 8)

        ax1.set_xlabel(r'$\mu^*$', fontsize=20)
        ax1.set_ylabel(r'$\sigma$', fontsize=20)
        ax1.grid()
        ax1.yaxis.grid(linestyle = '--', color = '0.75')
        ax1.xaxis.grid(linestyle = '--', color = '0.75')
        ax1.set_xlim((0.0, mustar2use.max()+mustar2use.max()*0.1))
        ax1.set_ylim((0.0, sigma2use.max()+sigma2use.max()*0.1))

        majloc1 = MaxNLocator(nbins=4, prune='lower')
        ax1.yaxis.set_major_locator(majloc1)
        majloc2 = MaxNLocator(nbins=4)
        ax1.xaxis.set_major_locator(majloc2)

        if zoomperc != 'none':
            #the zooming box size is ad hoc and can be improved
            axins = zoomed_inset_axes(ax1, np.floor(1./zoomperc/2.5),
                                      loc = loc)

            axins.plot(mustar2use, sigma2use, 'ks', markersize = 3)
            transOffset2 = offset_copy(axins.transData, fig=plt.gcf(),
                                       x = -0.05, y=0.10, units='inches')
            #plot in the subplot
            ct2=0
            txtobjects2=[]
            for x, y in zip(mustar2use, sigma2use):
                if x < mustar2use.max()*zoomperc and y < sigma2use.max()*zoomperc:
                    axins.plot((x,),(y,), 'ks', markersize = 3)
                    ls = axins.text(x, y, '%s' %self._namelist[ct2],
                                  transform=transOffset2, color='k')
                    txtobjects2.append(ls)
                ct2+=1

            #zoomplot with labels right
            axins.yaxis.set_ticks_position('right')
            #set the limits of the zoom plot
            axins.set_xlim((0.0, mustar2use.max()*zoomperc))
            axins.set_ylim((0.0, sigma2use.max()*zoomperc))
            #only minor number of ticks for cleaner overview
            majloc3 = MaxNLocator(nbins=3, prune='lower')
            axins.yaxis.set_major_locator(majloc3)
            majloc4 = MaxNLocator(nbins=3, prune='lower')
            axins.xaxis.set_major_locator(majloc4)
            #smaller size for the ticklabels (different is actually not needed)
            for tickx in axins.xaxis.get_major_ticks():
                tickx.label.set_fontsize(10)
            for label in axins.yaxis.get_majorticklabels():
                label.set_fontsize(10)
                label.set_rotation('vertical')

            #create the subarea-plot in main frame and connect
            mark_inset(ax1, axins, loc1=2, loc2=4, fc='none', ec='0.8')
            axins.grid()
            axins.yaxis.grid(linestyle = '--', color = '0.85')
            axins.xaxis.grid(linestyle = '--', color = '0.85')
        return fig, ax1, txtobjects
Exemplo n.º 25
0
    def map_ssp_view(self):
        """plot all the ssp in the database"""

        view_rows = self._get_all_ssp_view_rows()
        if view_rows is None:
            raise DbError("Unable to retrieve ssp view rows > Empty database?")
        if len(view_rows) == 0:
            raise DbError("Unable to retrieve ssp view rows > Empty database?")

        # prepare the data
        ssp_x = list()
        ssp_y = list()
        ssp_label = list()
        for vr in view_rows:
            ssp_x.append(vr[b'cast_position'].x)
            ssp_y.append(vr[b'cast_position'].y)
            ssp_label.append(vr[b'pk'])
        ssp_x_min = min(ssp_x)
        ssp_x_max = max(ssp_x)
        ssp_x_mean = (ssp_x_min + ssp_x_max) / 2
        ssp_x_delta = max(0.05, abs(ssp_x_max - ssp_x_min)/5)
        ssp_y_min = min(ssp_y)
        ssp_y_max = max(ssp_y)
        ssp_y_mean = (ssp_y_min + ssp_y_max) / 2
        ssp_y_delta = max(0.05, abs(ssp_y_max - ssp_y_min)/5)
        log.info("data boundary: %.4f, %.4f (%.4f) / %.4f, %.4f (%.4f)"
                 % (ssp_x_min, ssp_x_max, ssp_x_delta, ssp_y_min, ssp_y_max, ssp_y_delta))

        # make the world map
        fig = plt.figure()
        #plt.title("SSP Map (%s profiles)" % len(view_rows))
        ax = fig.add_subplot(111)
        plt.ioff()

        wm = self._world_draw_map()
        # x, y = wm(ssp_x_mean, ssp_y_mean)
        # wm.scatter(x, y, s=18, color='y')

        if ssp_x_mean > 0:
            ssp_loc = 2
        else:
            ssp_loc = 1

        max_delta_range = max(abs(ssp_x_min-ssp_x_max),abs(ssp_y_min-ssp_y_max))
        log.info("maximum delta range: %s" % max_delta_range)
        if max_delta_range > 15:
            ins_scale = 6
        elif max_delta_range > 12:
            ins_scale = 9
        elif max_delta_range > 6:
            ins_scale = 12
        elif max_delta_range > 3:
            ins_scale = 15
        else:
            ins_scale = 18
        ax_ins = zoomed_inset_axes(ax, ins_scale, loc=ssp_loc)
        ax_ins.set_xlim((ssp_x_min - ssp_x_delta), (ssp_x_max + ssp_x_delta))
        ax_ins.set_ylim((ssp_y_min - ssp_y_delta), (ssp_y_max + ssp_y_delta))

        m = self._inset_draw_map(llcrnrlon=(ssp_x_min - ssp_x_delta), llcrnrlat=(ssp_y_min - ssp_y_delta),
                                 urcrnrlon=(ssp_x_max + ssp_x_delta), urcrnrlat=(ssp_y_max + ssp_y_delta),
                                 ax_ins=ax_ins)

        x, y = m(ssp_x, ssp_y)
        m.scatter(x, y, marker='o', s=16, color='r')
        m.scatter(x, y, marker='.', s=1, color='k')

        if ssp_x_mean > 0:
            mark_inset(ax, ax_ins, loc1=1, loc2=4, fc="none", ec='y')
        else:
            mark_inset(ax, ax_ins, loc1=2, loc2=3, fc="none", ec='y')

        ax_ins.tick_params(color='y', labelcolor='y')
        for spine in ax_ins.spines.values():
            spine.set_edgecolor('y')

        #fig.tight_layout()
        plt.show()
Exemplo n.º 26
0
axmain[2].text(0.02,0.02,'Impedance\n mismatched',transform=axmain[2].transAxes)
axx[2].set_ylim((-0.35,0.35))
axy[2].set_xlim((-0.2,0.2))
axx[2].xaxis.set_label_coords(1, -0.5)

# Bottom right
axmain[3].text(0.98,0.02,'Both\n mismatched',horizontalalignment='right',transform=axmain[3].transAxes)
axx[3].set_ylim((-0.27,0.27))
axy[3].set_xlim((-0.21,0.21))


#Inset
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

axins = zoomed_inset_axes(axmain[2],6,loc=1)


#skip = 1
#K = np.loadtxt('K.txt')
#rho = np.loadtxt('rho.txt')[::skip,::skip]
#eps = np.loadtxt('sw4_q0.txt')[::skip,::skip]
#sigma = np.exp(K*eps[-1])-1
#xmom = np.loadtxt('sw4_q1.txt')[::skip,::skip]
#ymom = np.loadtxt('sw4_q2.txt')[::skip,::skip]
#u = xmom/rho
#v = ymom/rho
#x = np.linspace(0,150,9600)
#y = np.linspace(0,1,128)
#X,Y = np.meshgrid(x,y,indexing='ij')
#x_skip = 8
Exemplo n.º 27
0
def map_showXY(map12,map12m,map12my,map12mx,map13,map13m,map18,map18m,ta12,ta13,Tx12,Tx13,Tx18,wcs,y,x,dy,dx,dv,gf,s):
    """
    To use with IPython interact
    """

    #===================================Fitting======================
    #gf=0.2 #gooud fit parameter ~10%
    index_deviation=[10,2] #Max and Min Index Deviation for Second Derivative Mask
    xx=velocity
    #===========CO12=======================
    s12=Spectra(map12,y,x)
    #----mask------
    der2=np.diff(s12,2.) #Second Derivative
    m = np.ones(len(s12), dtype=bool)
    ind1=np.argsort(der2)[0]+1
    ind2=np.argsort(der2)[1]+1
    i=0
    while (np.abs(ind1-ind2)>index_deviation[0] or np.abs(ind1-ind2)<index_deviation[1]):
        #print np.abs(ind1-ind2),np.abs(ind1-ind2)>15
        ind2=np.argsort(der2)[i]+1
        i=i+1
    m[ind1:ind2]=False
    m[ind2:ind1]=False
    #---end of mask-----
    try:
        popt12, pcov12 = curve_fit(gaussian, xx[m], s12[m],p0=[s12.max(),xx[np.argmax(s12)],1.5],diag=(0.01,0.01))
    except:
        popt12,pcov12=np.zeros((3)),np.zeros((3,3))
    sd12= np.sqrt(np.diag(pcov12))      #Standard Deviation
    fit12 = (sd12<gf*np.abs(popt12)).all() #Good Fit?
    FWHM12=2.355*np.abs(popt12[2])      #Fitted Full Width Half Maximum
    FWTM12=1.865*FWHM12

    outflow=False
    if (FWTM12>4.):
	outflow=True

    FWHM12t=0.00001*2.355*np.sqrt(k_b*Tx12[y,x]/(m_CO12*amu)) #theoretical (thermal)
    ########################################
    # s912=Spectra9(map12,y,x)[0]
    # popt912, pcov912 = curve_fit(gaussian, xx, s912,p0=[s912.max(),xx[np.argmax(s12)],1.5],diag=(0.01,0.01))
    # sd912= np.sqrt(np.diag(pcov912))
    #===========CO13=======================
    s13=Spectra(map13,y,x)
    try:
        popt13, pcov13 = curve_fit(gaussian, xx, s13,p0=[0.25*popt12[0],popt12[1],popt12[2]],diag=(0.005,0.005))
    except:
        popt13,pcov13=np.zeros((3)),np.zeros((3,3))
    sd13= np.sqrt(np.diag(pcov13))      #Standard Deviation
    fit13 = (sd13<gf*np.abs(popt13)).all() #Good Fit?
    FWHM13=2.355*np.abs(popt13[2])      #Fitted Full Width Half Maximum
    FWHM13t=0.00001*2.355*np.sqrt(k_b*Tx13[y,x]/(m_CO13*amu)) #theoretical (thermal)
########################################################
    # s913=Spectra9(map13,y,x)[0]
    # popt913, pcov913 = curve_fit(gaussian, xx, s913,p0=[0.25*popt912[0],popt912[1],popt912[2]],diag=(0.1,0.1))
    # sd913= np.sqrt(np.diag(pcov913))
    #===========CO18=======================
    s18=Spectra(map18,y,x)
    try:
        popt18, pcov18 = curve_fit(gaussian, xx, s18,p0=[0.25*popt13[0],popt13[1],popt13[2]],diag=(0.001,0.001))
    except:
        popt18,pcov18=np.zeros((3)),np.zeros((3,3))
    sd18= np.sqrt(np.diag(pcov18))      #Standard Deviation
    fit18 = (sd18<gf*np.abs(popt18)).all() #Good Fit?
    FWHM18=2.355*np.abs(popt18[2])      #Fitted Full Width Half Maximum
    FWHM18t=0.00001*2.355*np.sqrt(k_b*Tx18[y,x]/(m_C18O*amu)) #theoretical (thermal)

    #================TABLE========================================
    col1=['$^{12}CO$ $T_{B}$','$^{13}CO$ $T_{B}$','$C^{18}O$ $T_{B}$',r'$\tau^{12}$',r'$\tau^{13}$','$^{12}CO$ $T_{X}$','$^{13}CO$ $T_{X}$',r'$^{12}CO$ FWHM',r'$^{12}CO$ FWTM',r'$^{13}CO$ FWHM',r'$C^{18}O$ FWHM',r'$^{12}CO$ Integral',r'$^{12}CO$ Core Integral', r'$^{12}CO$ Wings Integral','$^{12}CO$ Mass','$^{12}CO$ Core Mass','$^{12}CO$ Wings Mass',r'$^{12}CO$ Blue Wing Speed (Absolute)',r'$^{12}CO$ Red Wing Speed (Absolute)',r'$^{12}CO$ (Blue,Right) Wings Momentum']

    i12all=s12.sum()*vres
    i12b=s12[xx<popt13[1]-FWHM13/2].sum()*vres if fit13 else np.nan
    i12r=s12[xx>popt13[1]+FWHM13/2].sum()*vres if fit13 else np.nan
    i12=i12b+i12r
    #i12=(s12[xx<popt13[1]-FWHM13/2].sum()+s12[xx>popt13[1]+FWHM13/2].sum())*vres if fit13 else np.nan
    i12core=i12all-i12 if fit13 else np.nan
    Mb=Integral_to_mass(i12b,Tx12[y,x],ta12[y,x]) if i12b else np.nan
    Mr=Integral_to_mass(i12r,Tx12[y,x],ta12[y,x]) if i12r else np.nan
    MG= Integral_to_mass(i12,Tx12[y,x],ta12[y,x]) if i12 else np.nan
    MGall=Integral_to_mass(i12all,Tx12[y,x],ta12[y,x]) if i12 else np.nan
    MGcore=Integral_to_mass(i12core,Tx12[y,x],ta12[y,x]) if i12 else np.nan

    Vrel=popt13[1]
    xx1=np.logical_and(xx<=Vrel-FWHM13/2,xx>=Vrel-10.)
    xx2=np.logical_and(xx>=Vrel+FWHM13/2,xx<=Vrel+10.)

    Vb=(xx[xx1]*s12[xx1]).sum()/s12[xx1].sum()
    Vr=(xx[xx2]*s12[xx2]).sum()/s12[xx2].sum()
    Pb=Mb*Vb/np.cos(57.3)
    Pr=Mr*Vr/np.cos(57.3)

    if outflow:
        si='%0.2f $K\,km\,s^{-1}$'%i12
        sm='%0.2f $M_{\odot}$ ($M_{B}$: %0.2f, $M_{R}$: %0.2f) // Ratio (all): %0.2f (core): %0.2f'%(MG,Mb,Mr,MG/MGall,MG/MGcore)

        siall='%0.2f $K\,km\,s^{-1}$'%i12all
        small='%0.2f $M_{\odot}$'%MGall

        sicore='%0.2f $K\,km\,s^{-1}$'%i12core
        smcore='%0.2f $M_{\odot}$'%MGcore
    else:
        si='0.0 (%0.2f) $K\,km\,s^{-1}$'%i12
        sm='0.0 (%0.2f) $M_{\odot}$'%MG

        siall='0.0 (%0.2f) $K\,km\,s^{-1}$'%i12all
        small='0.0 (%0.2f) $M_{\odot}$'%MGall

        sicore='0.0 (%0.2f) $K\,km\,s^{-1}$'%i12core
        smcore='0.0 (%0.2f) $M_{\odot}$'%MGcore

    col2=np.array(['%0.2f'%map12m[y,x],'%0.2f'%map13m[y,x],'%0.2f'%map18m[y,x],'%0.2f'%ta12[y,x],'%0.2f'%ta13[y,x],'%0.2f K'%Tx12[y,x],'%0.2f K'%Tx13[y,x],'%0.2f $km\,s^{-1}$ (thermal: %0.2f)'%(FWHM12,FWHM12t),'%0.2f $km\,s^{-1}$'%FWTM12,'%0.2f $km\,s^{-1}$ (thermal: %0.2f)'%(FWHM13,FWHM13t),'%0.2f $km\,s^{-1}$ (thermal: %0.2f)'%(FWHM18,FWHM18t),siall,sicore,si,small,smcore,sm,'%0.2f (%0.2f) $km\,s^{-1}$'%(Vb-Vrel,Vb),'%0.2f (%0.2f) $km\,s^{-1}$'%(Vr-Vrel,Vr),'%0.2f,%0.2f // %0.2f $M_{\odot} km\,s^{-1}$'%(Pb,Pr,Pb+Pr)])

    t=Table([col1,col2],names=('Name','Value'),meta={'name': 'first table'})
    display(t)
    #col1=np.array(['$^{12}CO$ $T_{B}$','%0.2f'%map12m[y,x]])
    #col2=np.array(['$^{13}CO$ $T_{B}$','%0.2f'%map13m[y,x]])
    #col3=np.array(['$C^{18}O$ $T_{B}$','%0.2f'%map18m[y,x]])
    #col4=np.array([r'$\tau^{12}$','%0.2f'%ta12[y,x]])
    #col5=np.array([r'$\tau^{13}$','%0.2f'%ta13[y,x]])
    #col6=np.array(['$^{12}CO$ $T_{X}$','%0.2f K'%Tx12[y,x]])
    #col7=np.array(['$^{13}CO$ $T_{X}$','%0.2f K'%Tx13[y,x]])
    #col8=np.array([r'$^{12}CO$ FWHM','%0.2f $km\,s^{-1}$ (thermal: %0.2f)'%(FWHM12,FWHM12t)])
    #col9=np.array([r'$^{13}CO$ FWHM','%0.2f $km\,s^{-1}$'%FWTM12])
    #col10=np.array(['$^{13}CO$ $T_{B}$','%0.2f $km\,s^{-1}$ (thermal: %0.2f)'%(FWHM13,FWHM13t)])
    #col11=np.array([r'$C^{18}O$ FWHM','%0.2f $km\,s^{-1}$ (thermal: %0.2f)'%(FWHM18,FWHM18t)])
    #col12=np.array([r'$^{12}CO$ Wings Integral',si])
    #col13=np.array(['$^{12}CO$ Wings Mass',sm])

    #t=Table([col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,col11,col12,col13])
    #display(t)
    #t.write('test.tex',format='latex')

    #================Print==============================================
    # print 'tau12: %0.3f'%ta12[y,x]
    # print 'tau13: %0.3f'%ta13[y,x]
    # print '12CO Excitation Temperature: %0.2f'%Tx12[y,x]
    # print '13CO Excitation Temperature: %0.2f'%Tx13[y,x]
    # print 'C18O Excitation Temperature: %0.2f'%Tx18[y,x]
    # print '12CO FWHM: %0.2f km/s || Theoretical (thermal): %0.2f km/s (Ratio:%0.2f) || Larson L: %0.2f pc || Larson M: %0.2f Mo'%(FWHM12,FWHM12t,FWHM12/FWHM12t,(FWHM12/1.1)**(1/0.38),(FWHM12/0.42)**(1/0.2))
    # print '13CO FWHM: %0.2f km/s || Theoretical (thermal): %0.2f km/s (Ratio:%0.2f) || Larson L: %0.2f pc || Larson M: %0.2f Mo'%(FWHM13,FWHM13t,FWHM13/FWHM13t,(FWHM13/1.1)**(1/0.38),(FWHM13/0.42)**(1/0.2))
    # print 'C18O FWHM: %0.2f km/s || Theoretical (thermal): %0.2f km/s (Ratio:%0.2f) || Larson L: %0.2f pc || Larson M: %0.2f Mo'%(FWHM18,FWHM18t,FWHM18/FWHM18t,(FWHM18/1.1)**(1/0.38),(FWHM18/0.42)**(1/0.2))
    # if fit13:
    #     print 'Wings Integral in $^{12}CO$: %0.2f K'%(s12[xx<popt13[1]-FWHM13/2].sum()+s12[xx>popt13[1]+FWHM13/2].sum())

    #===========================================================================
    #===========PLOTS=======================
    #===========================================================================
    plt.rcParams['figure.figsize'] = 22, 35
    #dy,dx,dv=20,20,10
    vmax=np.argmax(s13)
    v1,v2=vmax-dv,vmax+dv

    #===========================================
    #===Map=====================================
    gs = gridspec.GridSpec(11, 8)

    #====ax1-Main Map===============================
    ax1=plt.subplot(gs[1:5,2:7])    #Axis for Main Map
    ax1.set_title('$^{12}CO$ Excitation Temperatures')
    #mim=ax1.imshow(map12m,origin='low',cmap='coolwarm')
    mim=ax1.imshow(Tx12.data,origin='low',cmap='coolwarm')       #Excitation Map
    ax1.axvline(x=x,color='k',ls='dashed',linewidth=1.0,alpha=0.6) #Current X
    ax1.annotate('$x$=%d'%x,(x+5,5),color='k',size=20)
    ax1.axhline(y=y,color='k',ls='dashed',linewidth=1.0,alpha=0.6)  #Current Y
    ax1.annotate('$y$=%d'%y,(5,y+5),color='k',size=20)
    ax1bar = inset_axes(ax1, width='2%', height='40%', loc=4)   #axis for colorbar
    ax1.annotate(s='', xy=(530,40), xytext=(579,40), arrowprops={'arrowstyle':'|-|','linewidth':2.0})
    ax1.text(542,43,'3 pc',color='white',fontsize=15)
    plt.colorbar(mim,cax=ax1bar)        #colorbar

    #=====================================
    axv0=plt.subplot(gs[0,2:7],sharex=ax1) #Axis for (X,Velocity) Map
    axv0.set_title('              $^{12}CO$ Max $T_{B}$')
    lev=np.linspace(0,map12mx.max(),20)     #Contourf Levels
    mimx=axv0.contourf(np.arange(0,map12mx.shape[1]),velocity,map12mx,levels=lev,cmap='coolwarm')
    axv0.xaxis.tick_top()
    axv0.axvline(x=x,color='k',ls='dashed',linewidth=1.0,alpha=0.75) #Current X

    axv1=plt.subplot(gs[1:5,7],sharey=ax1)  #Axis for (X,Velocity) Map
    axv1.set_title('$^{12}CO$ Max $T_{B}$')
    lev=np.linspace(0,map12my.max(),20)     #Contourf Levels
    mimx=axv1.contourf(velocity,np.arange(0,map12my.shape[1]),np.rot90(map12my,3),levels=lev,cmap='coolwarm')
    axv1.yaxis.tick_right()
    axv1.axhline(y=y,color='k',ls='dashed',linewidth=1.0,alpha=0.75) #Current Y

    #===========================
    #==Zoom=======
    x1, x2, y1, y2 = x-dx, x+dx, y-dy, y+dy     #Define Region
    region12=map12m[y1:y2,x1:x2]
    region13=map13m[y1:y2,x1:x2]
    if ((x+dx>350) and (y+dy>250)):     #dx=20, 7
        axins = zoomed_inset_axes(ax1, 140./np.max([dx,dy]), loc=3) #Axis for Zoom
    else:
        axins = zoomed_inset_axes(ax1, 140./np.max([dx,dy]), loc=1) #Axis for Zoom
    #axins.set_title('$^{12}CO$ and $^{13}CO$ (contours) \n max$T_{B}$ $(K)$')
    c12=axins.contourf(map12m,levels=np.linspace(region12.min(),region12.max(),15))
    c13=axins.contour(map13m,cmap='gnuplot',levels=np.linspace(region13.min(),region13.max(),7),alpha=0.75)
    axins.set_xlim(x1, x2)
    axins.set_ylim(y1, y2)
    mark_inset(ax1, axins, loc1=2, loc2=3, fc="none", ec="1.",lw=2.)

    axins.set_title('Max $T_{B}$ Contours:$^{13}CO$ \n Max $T_{B}$ Filled Contours:$^{12}CO$ ')
    # axins12 = inset_axes(axins, width='2%', height='25%', loc=2)
    # cbar12=plt.colorbar(c12,cax=axins12)
    # cbar12.ax.set_title('$^{12}CO$ \n maxT $(K)$')
    #
    # axins13 = inset_axes(axins, width='2%', height='25%', loc=1)
    # cbar13=plt.colorbar(c13,cax=axins13)
    # cbar13.ax.set_title('$^{13}CO$ \n maxT $(K)$')

    #==Map-Rectangles
    dd=0.5
    rect1 = [Rectangle((x-dx,y-dd), width=2.*dx, height=2.*dd, fill=False,color='red',linewidth=1.2,alpha=0.75)]
    axins.add_artist(rect1[0])
    rect2 = [Rectangle((x-dd,y-dy), width=2.*dd, height=2.*dy, fill=False,color='red',linewidth=1.2,alpha=0.75)]
    axins.add_artist(rect2[0])
    rect3= [Rectangle((x-1.5,y-1.5), width=3, height=3, fill=False,color='green',linewidth=1.5,alpha=0.95)]
    axins.add_artist(rect3[0])

    #=================3D Velocities==================================================
    #Parameters
    hl_lw=3 #Highlight LineWidth
    lev_18 = [popt18[0]/2.] #C18O Contour Display
    lev_13 = popt13[0]/2. #CO13 Contour Display
    min13=0.75
    min12=0.
    num_levels_12=10
    num_levels_13=8
    #======X-line=========================
    ax1y=plt.subplot(gs[5:7,2:])
    ax1y.set_ylabel('Velocity $(km\,s^{-1})$')
    ax1y.set_xlabel('X-Pixel')
    region13y=map13[v1:v2,y,x-dx:x+dx] #CO13 zoom region
    region12y=map12[v1:v2,y,x-dx:x+dx] #CO12 zoom region
    region18y=map18[v1:v2,y,x-dx:x+dx] #CO18 zoom region

    lev13y = np.linspace(np.abs(region13y.min())+min13,region13y.max(),num_levels_13)
    lev12y = np.linspace(min12,region12y.max(),num_levels_12)
    lev18y=lev_18

    cy=ax1y.contour(np.arange(x-dx,x+dx,1),velocity[v1:v2],region13y,levels=lev13y,linewidths=2.1,cmap='gnuplot',alpha=0.8)
    if fit13:
        ax1y.contour(np.arange(x-dx,x+dx,1),velocity[v1:v2],region13y,[lev_13],linestyles='--',linewidths=hl_lw,colors='red',alpha=1.)
    c2y=ax1y.contourf(np.arange(x-dx,x+dx,1),velocity[v1:v2],region12y,levels=lev12y)
    if fit18:
        ax1y.contour(np.arange(x-dx,x+dx,1),velocity[v1:v2],region18y,lev18y,linestyles='--',linewidths=hl_lw,colors='black',alpha=0.8)
        ax1y.contour(np.arange(x-dx,x+dx,1),velocity[v1:v2],region18y,[s18.max()*0.8],linewidths=hl_lw+1,colors='black',alpha=0.8)

    ax1y.plot(np.ones(velocity[v1:v2].shape)*x,velocity[v1:v2],'--')

    #===CO12 Colorbar Hacks======================================
    axinsy12 = inset_axes(ax1y, width='35%', height='3%', loc=2)
    cbary12=plt.colorbar(c2y,cax=axinsy12,orientation='horizontal')
    cbary12.ax.set_title('$^{12}CO$ $T_{B}$ $(K)$')

    #===CO13 Colorbar Hacks======================================
    axinsy13 = inset_axes(ax1y, width='30%', height='3%', loc=1)
    cbary13=plt.colorbar(cy,cax=axinsy13,orientation='horizontal')
    cbary13.ax.set_title('$^{13}CO$ $T_{B}$ $(K)$')

    #==========Y-line===============================================================
    ax1x=plt.subplot(gs[1:5,:2])
    ax1x.set_xlabel('Velocity $(km\,s^{-1})$')
    ax1x.set_ylabel('Y-Pixel')
    region13x=map13[v1:v2,y-dy:y+dy,x]
    region12x=map12[v1:v2,y-dy:y+dy,x]
    region18x=map18[v1:v2,y-dy:y+dy,x]

    lev13x = np.linspace(np.abs(region13x.min())+min13,region13x.max(),num_levels_13)
    lev12x = np.linspace(min12,region12x.max(),num_levels_12)
    lev18x=lev_18

    cx=ax1x.contour(velocity[v1:v2],np.arange(y-dy,y+dy),np.rot90(region13x,3),levels=lev13x,linewidths=2.1,cmap='gnuplot',alpha=0.8)
    if fit13:
        ax1x.contour(velocity[v1:v2],np.arange(y-dy,y+dy),np.rot90(region13x,3),[lev_13],linestyles='--',linewidths=hl_lw,colors='red',alpha=1.)
    c2x=ax1x.contourf(velocity[v1:v2],np.arange(y-dy,y+dy),np.rot90(region12x,3),levels=lev12x)
    if fit18:
        ax1x.contour(velocity[v1:v2],np.arange(y-dy,y+dy),np.rot90(region18x,3),lev18x,linestyles='--',linewidths=hl_lw,colors='black',alpha=0.8)
        ax1x.contour(velocity[v1:v2],np.arange(y-dy,y+dy),np.rot90(region18y,3),[s18.max()*0.8],linewidths=hl_lw+1,colors='black',alpha=0.8)
    ax1x.plot(velocity[v1:v2],np.ones(velocity[v1:v2].shape)*y,'--')

    #===CO12 Colorbar Hacks======================================
    axinsx12 = inset_axes(ax1x, width='3%', height='30%', loc=2)
    cbarx12=plt.colorbar(c2x,cax=axinsx12)
    cbarx12.ax.set_title('$^{12}CO$ \n  $T_{B}$ $(K)$')

    #===CO13 Colorbar Hacks======================================
    axinsx13 = inset_axes(ax1x, width='3%', height='30%', loc=1)
    cbarx13=plt.colorbar(cx,cax=axinsx13)
    cbarx13.ax.set_title('$^{13}CO$ \n $T_{B}$ $(K)$')
    axinsx13.yaxis.set_ticks_position("left")

    #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    #============================================================================
    x_p=xx.min()
    #x_mean= xx.mean() #For Text Annotation

    ax2=plt.subplot(gs[7,:])
    y_p=s12.max()
    ax2.set_title('$^{12}CO$ // $FWHM=$%0.3f'%(FWHM12))
    ax2.plot(xx,s12,label='CO12')
    ax2.plot(xx[m],s12[m],'ko',label='Masked CO12 Data')
    ax2.plot(xx,gaussian(xx,popt12[0],popt12[1],popt12[2]),label='Fit to Masked Data')
    if fit12:
        ax2.fill_between(xx,gaussian(xx,popt12[0]-sd12[0],popt12[1]-sd12[1],popt12[2]-sd12[2]),gaussian(xx,popt12[0]+sd12[0],popt12[1]+sd12[1],popt12[2]+sd12[2]),alpha=0.25)
    ax2.annotate(r'Fit Parameters for CO12: $A=$%0.3f +/-%0.3f, $x_0=$%0.3f +/-%0.3f, $\sigma=$%0.3f +/-%0.3f'%(popt12[0],sd12[0],popt12[1],sd12[1],popt12[2],sd12[2]),(x_p,y_p))
    hline=np.linspace(popt12[1]-FWHM12/2,popt12[1]+FWHM12/2,10)
    ax2.plot(hline,np.ones(hline.shape)*popt12[0]/2,color='r',label='HalfMaximum of fit CO12')
    ax2.plot(xx,s13,alpha=0.7,label='CO13')
    ax2.plot(xx,s18,alpha=0.5,label='C18O')
    if fit18:
        ax2.axvspan(popt18[1]-FWHM18/2.,popt18[1]+FWHM18/2.,alpha=0.15)
    if fit13:
        ax2.axvspan(popt13[1]-FWHM13/2.,popt13[1]+FWHM13/2.,alpha=0.15,color='green')
    ax2.legend()

    ax3=plt.subplot(gs[8,:],sharex=ax2)
    y_p=s13.max()
    ax3.set_title('$^{13}CO$ // $FWHM=$%0.3f'%(FWHM13))
    ax3.plot(xx,s13,'ko',label='CO13')
    ax3.plot(xx,gaussian(xx,popt13[0],popt13[1],popt13[2]),label='Fit to CO13')
    if fit13:
        ax3.fill_between(xx,gaussian(xx,popt13[0]-sd13[0],popt13[1]-sd13[1],popt13[2]-sd13[2]),gaussian(xx,popt13[0]+sd13[0],popt13[1]+sd13[1],popt13[2]+sd13[2]),alpha=0.25)
    ax3.annotate(r'Fit Parameters for CO13: $A=$%0.3f +/-%0.3f, $x_0=$%0.3f +/-%0.3f, $\sigma=$%0.3f +/-%0.3f'%(popt13[0],sd13[0],popt13[1],sd13[1],popt13[2],sd13[2]),(x_p,y_p))
    hline=np.linspace(popt13[1]-FWHM13/2,popt13[1]+FWHM13/2,10)
    ax3.plot(hline,np.ones(hline.shape)*popt13[0]/2,color='r',label='HalfMaximum of fit CO13')
    ax3.plot(xx,s18,alpha=0.5,label='C18O')
    if fit18:
        ax3.axvspan(popt18[1]-FWHM18/2,popt18[1]+FWHM18/2,alpha=0.15)
    if fit13:
        ax3.axvspan(popt13[1]-FWHM13/2.,popt13[1]+FWHM13/2.,alpha=0.15,color='green')
    ax3.legend()

    ax4=plt.subplot(gs[9,:],sharex=ax2)
    y_p=s18.max()
    ax4.set_title(r'$C^{18}O$ // $FWHM=$%0.3f'%(FWHM18))
    ax4.plot(xx,s18,'ko',label='C18O')
    if fit18:
        ax4.plot(xx,gaussian(xx,popt18[0],popt18[1],popt18[2]),label='Fit to CO18')
        ax4.fill_between(xx,gaussian(xx,popt18[0]-sd18[0],popt18[1]-sd18[1],popt18[2]-sd18[2]),gaussian(xx,popt18[0]+sd18[0],popt18[1]+sd18[1],popt18[2]+sd18[2]),alpha=0.25)
        ax4.annotate(r'Fit Parameters for CO18: $A=$%0.3f +/-%0.3f, $x_0=$%0.3f +/-%0.3f, $\sigma=$%0.3f +/-%0.3f'%(popt18[0],sd18[0],popt18[1],sd18[1],popt18[2],sd18[2]),(x_p,y_p))
        hline=np.linspace(popt18[1]-FWHM18/2,popt18[1]+FWHM18/2,10)
        ax4.plot(hline,np.ones(hline.shape)*popt18[0]/2,color='r',label='HalfMaximum of fit CO18')
        ax4.axvspan(popt18[1]-FWHM18/2,popt18[1]+FWHM18/2,alpha=0.15)
    ax4.legend()

    ax5=plt.subplot(gs[10,:],sharex=ax2)

    ax5.set_title(r'$^{12}CO$ Wings')
    ax5.fill_between(xx[xx1],s12[xx1],alpha=0.7,color='blue')
    ax5.fill_between(xx[xx2],s12[xx2],alpha=0.7,color='red')
    if outflow:
        ax5.annotate(r'Outflow Mass Estimation: %0.2f $M_{\odot}$'%MG,(x_p,s12.max()-2),fontsize=17)
        ax5.annotate(r'Outflow Momentum Estimation: %0.2f $M_{\odot}\, km \, s^{-1}$'%(Pb+Pr),(x_p,s12.max()-0.4*s12.max()),fontsize=17)
        ax5.annotate(r'Blue Outflow: %0.2f $M_{\odot}$'%Mb,(popt13[1]-10,y_p),fontsize=13)
        ax5.annotate(r'$V_B:$ %0.2f $km\,s^{-1}$'%Vb,(Vb,y_p+5),fontsize=12)
        ax5.annotate(r'$V_R:$ %0.2f $km\,s^{-1}$'%Vr,(Vr,y_p+5),fontsize=12)
        ax5.annotate(r'Red Outflow: %0.2f $M_{\odot}$'%Mr,(popt13[1]+5,y_p),fontsize=13)
        ax5.vlines(Vb,0,s12.max())
        ax5.vlines(Vr,0,s12.max())

    #ax6=plt.subplot(gs[11:,:],sharex=ax2)
    #ax6.set_title('3X3 Mean and Standard Deviation Spectrum')
    #ave12=Spectra9(map12,y,x)
    #ave13=Spectra9(map13,y,x)
    #ave18=Spectra9(map18,y,x)
    #ax6.plot(xx,ave12[0],color='blue',label='CO12 Mean')
    #ax6.fill_between(xx,ave12[0]-ave12[1],ave12[0]+ave12[1],color='blue',alpha=0.25)
    #ax6.plot(xx,ave13[0],color='green',label='CO12 Mean')
    #ax6.fill_between(xx,ave13[0]-ave13[1],ave13[0]+ave13[1],color='green',alpha=0.25)
    #ax6.plot(xx,ave18[0],color='red',label='CO12 Mean')
    #ax6.fill_between(xx,ave18[0]-ave18[1],ave18[0]+ave18[1],color='red',alpha=0.25)
    # ax6.plot(xx,gaussian(xx,popt913[0],popt913[1],popt913[2]),'--',linewidth=3.,label='Fit')
    #ax6.legend()

    plt.tight_layout()
    if s:
        plt.savefig('full%d-%d'%(y,x),bbox_inches='tight')
Exemplo n.º 28
0
Arquivo: plot.py Projeto: senen2/aidd
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3, 4, -4, 3)

fig, ax = plt.subplots(figsize=[5, 4])

# prepare the demo image
Z, extent = get_demo_image()
Z2 = np.zeros([150, 150], dtype="d")
ny, nx = Z.shape
Z2[30:30 + ny, 30:30 + nx] = Z

# extent = [-3, 4, -4, 3]
ax.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6
axins.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")

# sub region of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
plt.xticks(visible=False)
plt.yticks(visible=False)

# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.draw()
plt.show()
Exemplo n.º 29
0
    # and for Gibraltar
    patch = create_rect_patch(coordinates3, m, 0.2)
    ax.add_patch(patch)

    # CTD and gliders
    # m.plot(lonCTD,latCTD,'ko',ms=1, zorder=6)

    # Coastline and continent
    m.plot(loncoast2, latcoast2, "k-", lw=0.1, zorder=4)
    m.fillcontinents(ax=ax, color="0.9", zorder=2)

    plt.title(r"25$-$31 May, 2014", fontsize=20)

    # Plot inset with CTD and gliders
    if doplotinset:
        axins = zoomed_inset_axes(ax, 4.5, loc=2)
        n1, n2 = m(coordinates2[0], coordinates2[2])
        n3, n4 = m(coordinates2[1], coordinates2[3])
        axins.set_xlim(n1, n3)
        axins.set_ylim(n2, n4)
        plt.gca().xaxis.set_major_locator(plt.NullLocator())
        plt.gca().yaxis.set_major_locator(plt.NullLocator())

        # Add gliders tracks and CTD casts
        NN = 34

        axins.plot(
            lonCTD[:NN],
            latCTD[:NN],
            "ks-",
            lw=0.5,
Exemplo n.º 30
0
                     axes_class=(pywcsgrid2.Axes, dict(header=h)))

    main_axes = grid[0]
    main_axes.locator_params(nbins=5)

    cb_axes = grid.cbar_axes[0] # colorbar axes

    im = main_axes.imshow(d, origin="lower", cmap=plt.cm.gray_r,
                          vmin=4.e-05, vmax=0.00018,
                          interpolation="nearest")

    cb_axes.colorbar(im)
    cb_axes.axis["right"].toggle(ticklabels=False)

    axins = zoomed_inset_axes(main_axes, zoom=3, loc=1,
                              axes_class=pywcsgrid2.Axes,
                              axes_kwargs=dict(wcs=h))

    im2 = axins.imshow(d, origin="lower", interpolation="nearest",
                       vmin=9.e-05, vmax=18.e-05,
                       cmap=plt.cm.gray_r)

    axins.set_xlim(120, 160)
    axins.set_ylim(120, 160)

    axins.set_ticklabel_type("delta")

    axins.axis[:].invert_ticklabel_direction()

    mark_inset(main_axes, axins, loc1=2, loc2=4, fc="none", ec="0.5")
Exemplo n.º 31
0
axes[0].axis(False)
axes = axes[1]

# Plot over whole domain
levels = 51
cbar = figure.colorbar(tricontourf(eta0,
                                   levels=levels,
                                   axes=axes,
                                   cmap='coolwarm'),
                       ax=axes)
cbar.set_label(r"Dislocation $[\mathrm m]$")
op.annotate_plot(axes)
axes.axis(False)

# Add zoom
axins = zoomed_inset_axes(axes, 2.5, bbox_to_anchor=[750,
                                                     525])  # zoom-factor: 2.5
tricontourf(eta0, levels=51, axes=axins, cmap='coolwarm')
axins.axis(False)
axins.set_xlim(xlim)
axins.set_ylim(ylim)
mark_inset(axes, axins, loc1=1, loc2=1, fc="none", ec="0.5")

# Save
fname = "dislocation_{:d}_{:s}".format(level, categories)
if not loaded:
    fname += '_ig'
savefig(fname, "plots", extensions=["jpg"], tight=False)

# --- Setup tsunami propagation problem

b = Function(P1).assign(op.set_bathymetry(P1))