Esempio n. 1
0
def test_rotation_mode(fig, mode, subplot_location):
    ha_list = "left center right".split()
    va_list = "top center baseline bottom".split()
    grid = ImageGrid(fig, subplot_location,
                    nrows_ncols=(len(va_list), len(ha_list)),
                    share_all=True, aspect=True, #label_mode='1',
                    cbar_mode=None)

    for ha, ax in zip(ha_list, grid.axes_row[-1]):
        ax.axis["bottom"].label.set_text(ha)

    grid.axes_row[0][1].set_title(mode, size="large")

    for va, ax in zip(va_list, grid.axes_column[0]):
        ax.axis["left"].label.set_text(va)

    i = 0
    for va in va_list:
        for ha in ha_list:
            ax = grid[i]
            for axis in ax.axis.values():
                axis.toggle(ticks=False, ticklabels=False)

            ax.text(0.5, 0.5, "Tpg",
                    size="large", rotation=40,
                    bbox=dict(boxstyle="square,pad=0.",
                              ec="none", fc="0.5", alpha=0.5),
                    ha=ha, va=va,
                    rotation_mode=mode)
            ax.axvline(0.5)
            ax.axhline(0.5)
            i += 1
Esempio n. 2
0
    def show(self, filename=None):
        self.fig = fig = P.figure(self.fignum, self.figsize)
        P.clf()

        header = self.maps[0].header

        self.grid = grid = ImageGrid(fig, (1, 1, 1),
                                     nrows_ncols=(self.nrows, self.ncols),
                                     share_all=True,
                                     axes_class=(pywcsgrid2.Axes,
                                                 dict(header=header)),
                                     **self.grid_kwargs)

        for i, (map, lower, upper) in enumerate(
                zip(self.maps, self.lower_energies, self.upper_energies)):
            map.show(axes=grid[i], cax=grid[i].cax)
            format_energy = lambda x: '%.1f' % (
                x / 1000.) if x < 1000 else '%.0f' % (x / 1000.)
            lower_string = format_energy(lower)
            upper_string = format_energy(upper)
            grid[i].add_inner_title("%s-%s GeV" % (lower_string, upper_string),
                                    loc=2)

        if self.title is not None:
            fig.suptitle(self.title)

        tight_layout(fig)
        if filename is not None: P.savefig(filename)
Esempio n. 3
0
def plot_tz_all(sims,
                models,
                field,
                fig=None,
                boundary=False,
                sp='tot',
                ph='whole',
                ismcut=10,
                **kwargs):
    nmodel = len(models)
    if fig is None: fig = plt.figure(figsize=(10, 2.5 * nmodel), num=0)
    g = ImageGrid(fig,
                  111, (nmodel, 1),
                  aspect=False,
                  axes_pad=0.1,
                  cbar_mode='single',
                  cbar_pad=0.2,
                  cbar_size='1%')
    iax = 0

    for m in models:
        dc = sims.dc[m]
        ax = g[iax]
        q = get_tz_field(dc, field, sp, ph)
        if (sp == 'ism') and (ismcut > 0):
            q = q.where(dc.ism['A'].sel(phase=ph) > ismcut)
        t = q.taxis * dc.to_Myr
        z = q.zaxis / 1.e3
        s = dc.tot['s4'].sel(phase='whole') / dc.tot['d'].sel(phase='whole')

        plt.sca(ax)

        #if field in ['massflux','energyflux','massflux_ratio','energyflux_ratio']:
        #    _im = plt.pcolormesh(t,z,-q)
        #    if 'norm' in kwargs: _im.set_norm(kwargs['norm'])
        #    if 'cmap' in kwargs: _im.set_cmap(plt.cm.Blues)
        if sp == 'icm':
            im = plt.pcolormesh(t, z, q.where(s > 1.e-15))
        else:
            im = plt.pcolormesh(t, z, q)
        if 'norm' in kwargs: im.set_norm(kwargs['norm'])
        if 'cmap' in kwargs: im.set_cmap(kwargs['cmap'])
        plt.axhline(0, ls=':', lw=3)
        plt.ylabel(r'$z [{\rm kpc}]$')

        if boundary:
            bc = (((s > 0.5) * s.zaxis).where(s > 0.5)).max(dim='zaxis') / 1.e3
            plt.plot(bc.taxis * dc.to_Myr, bc, color='#32cd32', lw=3, ls='-')

        plt.annotate(dc.name, (0.02, 0.95),
                     xycoords='axes fraction',
                     ha='left',
                     va='top',
                     **texteffect('x-small'))
        iax += 1
    ax.set_xlabel(r'$t [{\rm Myr}]$')
    cbar = plt.colorbar(im, cax=g[0].cax)
    if 'label' in kwargs: cbar.set_label(kwargs['label'])
    return fig, cbar
Esempio n. 4
0
def test_rotation_mode(fig, mode, subplot_location):
    ha_list = ["left", "center", "right"]
    va_list = ["top", "center", "baseline", "bottom"]
    grid = ImageGrid(fig,
                     subplot_location,
                     nrows_ncols=(len(va_list), len(ha_list)),
                     share_all=True,
                     aspect=True,
                     cbar_mode=None)

    # labels and title
    for ha, ax in zip(ha_list, grid.axes_row[-1]):
        ax.axis["bottom"].label.set_text(ha)
    for va, ax in zip(va_list, grid.axes_column[0]):
        ax.axis["left"].label.set_text(va)
    grid.axes_row[0][1].set_title(f"rotation_mode='{mode}'", size="large")

    if mode == "default":
        kw = dict()
    else:
        kw = dict(
            bbox=dict(boxstyle="square,pad=0.", ec="none", fc="C1", alpha=0.3))

    # use a different text alignment in each axes
    texts = []
    for (va, ha), ax in zip([(x, y) for x in va_list for y in ha_list], grid):
        # prepare axes layout
        for axis in ax.axis.values():
            axis.toggle(ticks=False, ticklabels=False)
        ax.axis([0, 1, 0, 1])
        ax.axvline(0.5, color="skyblue", zorder=0)
        ax.axhline(0.5, color="skyblue", zorder=0)
        ax.plot(0.5, 0.5, color="C0", marker="o", zorder=1)

        # add text with rotation and alignment settings
        tx = ax.text(0.5,
                     0.5,
                     "Tpg",
                     size="x-large",
                     rotation=40,
                     horizontalalignment=ha,
                     verticalalignment=va,
                     rotation_mode=mode,
                     **kw)
        texts.append(tx)

    if mode == "default":
        # highlight bbox
        fig.canvas.draw()
        for ax, tx in zip(grid, texts):
            bb = tx.get_window_extent().inverse_transformed(ax.transData)
            rect = plt.Rectangle((bb.x0, bb.y0),
                                 bb.width,
                                 bb.height,
                                 facecolor="C1",
                                 alpha=0.3,
                                 zorder=2)
            ax.add_patch(rect)
Esempio n. 5
0
def test_rotation_mode(fig, mode, subplot_location):
    ha_list = "left center right".split()
    va_list = "top center baseline bottom".split()
    grid = ImageGrid(
        fig,
        subplot_location,
        nrows_ncols=(len(va_list), len(ha_list)),
        share_all=True,
        aspect=True,
        # label_mode='1',
        cbar_mode=None)

    for ha, ax in zip(ha_list, grid.axes_row[-1]):
        ax.axis["bottom"].label.set_text(ha)

    # create a grid of axes to display text on.
    grid.axes_row[0][1].set_title(mode, size="large")

    for va, ax in zip(va_list, grid.axes_column[0]):
        ax.axis["left"].label.set_text(va)

    # use a different horizontal and vertical alignment for the text in each
    # axes.
    i = 0
    for va in va_list:
        for ha in ha_list:
            ax = grid[i]
            for axis in ax.axis.values():
                axis.toggle(ticks=False, ticklabels=False)

            # add text to the axes. Set the rotation_mode, horizontal
            # alignment (ha) and vertical alignment (va).
            ax.text(0.5,
                    0.5,
                    "Tpg",
                    size="large",
                    rotation=40,
                    bbox=dict(boxstyle="square,pad=0.",
                              ec="none",
                              fc="0.5",
                              alpha=0.5),
                    ha=ha,
                    va=va,
                    rotation_mode=mode)
            ax.axvline(0.5)
            ax.axhline(0.5)
            i += 1
Esempio n. 6
0
    def show(self, filename=None):

        from mpl_toolkits.axes_grid1.axes_grid import ImageGrid
        import pywcsgrid2

        self.fig = fig = P.figure(self.fignum, self.figsize)
        P.clf()

        header = self.counts.pf[0].header

        self.grid = grid = ImageGrid(fig, (1, 1, 1),
                                     nrows_ncols=(1, 2),
                                     axes_pad=0.1,
                                     share_all=True,
                                     cbar_mode="single",
                                     cbar_pad="2%",
                                     cbar_location="right",
                                     axes_class=(pywcsgrid2.Axes,
                                                 dict(header=header)))

        # This is kind of ugly, but use show() once to set the max_intensity, then show again
        # with matching colormaps. Kluge, but in an unimportant function.
        def show():
            self.counts.show(axes=self.grid[0])
            self.model.show(axes=self.grid[1], cax=grid.cbar_axes[0])

        show()

        # Same colorscale kluge as in ROISmoothedBeforeAfter
        max_intensity = max(self.counts.max_intensity,
                            self.model.max_intensity)
        self.counts.max_intensity = self.model.max_intensity = max_intensity
        show()

        self.grid[0].add_inner_title("Counts", loc=2)
        self.grid[1].add_inner_title("Model", loc=2)

        tight_layout(self.fig)

        self.header = self.h = [self.counts.header, self.model.header]

        if filename is not None: P.savefig(filename)
Esempio n. 7
0
    def show(self, filename=None):

        from mpl_toolkits.axes_grid1.axes_grid import ImageGrid
        import pywcsgrid2

        self.fig = fig = P.figure(self.fignum, self.figsize)
        P.clf()

        header = self.smoothed_source.pf[0].header

        self.grid = grid = ImageGrid(fig, (1, 1, 1),
                                     nrows_ncols=(1, 2),
                                     axes_pad=0.1,
                                     share_all=True,
                                     cbar_mode="single",
                                     cbar_pad="2%",
                                     cbar_location="right",
                                     axes_class=(pywcsgrid2.Axes,
                                                 dict(header=header)))

        def show():
            self.smoothed_sources.show(axes=self.grid[0])
            self.smoothed_source.show(axes=self.grid[1], cax=grid.cbar_axes[0])

        show()

        # use same color scale for each plot
        max_intensity = max(self.smoothed_sources.max_intensity,
                            self.smoothed_source.max_intensity)
        self.smoothed_sources.max_intensity = self.smoothed_source.max_intensity = max_intensity

        show()

        tight_layout(self.fig)

        self.header = self.h = [
            self.smoothed_sources.header, self.smoothed_source.header
        ]

        if filename is not None: P.savefig(filename)
Esempio n. 8
0
    m = Basemap(resolution='i',
                projection='cyl',
                llcrnrlat=bbox[1] - buf,
                area_thresh=100000,
                urcrnrlat=bbox[-1] + buf,
                llcrnrlon=bbox[0] - buf,
                urcrnrlon=bbox[2] + buf)

    x_map, y_map = m(*np.meshgrid(lon, lat))

    axes_pad = .2
    cfig = plt.gcf()
    grid = ImageGrid(cfig,
                     111,
                     nrows_ncols=(1, 1),
                     axes_pad=axes_pad,
                     cbar_mode="single",
                     cbar_pad=.05,
                     cbar_location="bottom",
                     cbar_size='3%')
    levels = get_levels(da_ds_mthly.loc['2019-12-01'].values.ravel(),
                        diverging=False)
    cmap = 'viridis'
    m.ax = grid[0]
    cntr = m.contourf(x_map,
                      y_map,
                      da_ds_mthly.loc['2019-12-01'].values,
                      cmap=cmap)
    cbar = plt.colorbar(cntr, cax=grid.cbar_axes[0], orientation='horizontal')
    m.ax.set_title('Prcp Total: December 2019\nIPSL-CM5A-MR_rcp26_r1i1p1')
    m.drawcountries()
    m.drawcoastlines()
Esempio n. 9
0
def tfkernels_bins(kgrid,
                   x0grid=x0grid_def,
                   title="",
                   colors=['red', 'blue', 'green'],
                   pixscale=0.03):
    # Show the kernels on a 3 by 3 subplot grid
    # the lower bounds of each kernel shown is specified by x0grid[0], x0grid[1]
    # the order is in the order of subplot (x0grid[0][0] is upper left most, x0grid[0][-1]
    # is bottom right most
    if len(x0grid[0]) != 9:
        raise ValueError, "please give x0 for a 3 by 3 subplot grid"
    # x0grid: from top to bottom, from left to right
    # 1  2  3
    # 4  5  6
    # 7  8  9
    fig = plt.figure(figsize=(10, 9))
    imgrid = ImageGrid(fig,
                       111,
                       nrows_ncols=(3, 3),
                       axes_pad=0.03,
                       share_all=True)
    vmin = 1.e-6
    vmax = 2.e-3
    #prop = {'cmap':'hot','vmin':vmin,'vmax':vmax}
    prop = {'cmap': 'hot', 'origin': 'lower'}
    for i in range(9):
        #ax = plt.subplot(3,3,i+1)
        ax = imgrid[i]
        k = kernel_x0(kgrid, x0grid[0][i], x0grid[1][i])
        print "k", k.index
        kshape = shape(k.kernel)
        #ax.imshow(k.kernel.swapaxes(0,1),**prop)
        kmax = max(k.kernel.ravel())
        kseq = [0.9 * kmax, 0.5 * kmax, 0.1 * kmax]
        ax.contour(k.kernel.swapaxes(0, 1),
                   kseq,
                   colors=colors,
                   linewidths=2.0)
        ax.text(0.1,
                0.1,
                '[%.1f, %.1f]' % (k.x0_cell[0], k.x1_cell[0]),
                transform=ax.transAxes,
                font_properties=Helvetica(16))
        r0bin_as = pixscale * (10.**k.x0_cell[1])  # r0 of this bin in arcsec
        r1bin_as = pixscale * (10.**k.x1_cell[1])
        ax.text(0.1,
                0.9,
                '[%.2f\", %.2f\"]' % (r0bin_as, r1bin_as),
                transform=ax.transAxes,
                font_properties=Helvetica(16))
        #if i == 3:
        #   plt.ylabel('log10(Re_out/Re_in) [pixels]', size=18)
        #if i == 7:
        #   plt.xlabel('mag_out - mag_in', size=18)
        ax.plot([kshape[1] / 2], [kshape[0] / 2],
                '+',
                ms=20,
                mew=1.0,
                c='black')
        ax.set_xlim(0, kshape[1])
        ax.set_ylim(0, kshape[0])

        #plt.title('$%.1f<m_{in}<%.1f$' % (k.x0_cell[0],k.x1_cell[0]),size=11)
        #plt.ylabel('$%.1f<\log_{10}(R_e)<%.1f$' % (k.x0_cell[1],k.x1_cell[1]),size=11)

    for i in range(9):
        imgrid[i].set_yticks([14, 64, 114])
        #imgrid[i].tick_params(axis='y', color='white')
        if i in [0, 3, 6]:
            imgrid[i].set_yticklabels([-1, 0, 1], size=14, color='black')
            imgrid[i].axis["left"].label.set_text(r"$\delta \log R$")
            imgrid[i].axis["left"].label.set_size(20)
        if i in [2, 5, 8]:
            imgrid[i].axis["right"].label.set_text(r"$\delta \log R$")
            imgrid[i].axis["right"].label.set_size(20)
        #   ax2 = imgrid[i].twinx()
        #   yd1, yd2 = imgrid[i].yaxis.get_data_interval()
        #   ax2.yaxis.set_data_interval(yd1,yd2)
        #   yl1, yl2 = imgrid[i].get_ylim()
        #   ax2.set_ylim(yl1, yl2)
        #   #ax2.set_yticks([14,64,114])
        #   #ax2.set_yticklabels([-1,0,1],size=12,color='black')
        #   #ax2.tick_params(axis='y', color='white')
        #   ax2.yaxis.tick_right()
        #   ax2.set_ylabel(r"$\delta \log R$")
        #imgrid[i].yaxis.label.set_color('white')
        #plt.xlabel('$\delta m$', size=8)
        #plt.ylabel('$\delta \log R$', size=8)
        imgrid[i].set_xticks([14, 64, 114])
        imgrid[i].set_xticklabels([-1, 0, 1], size=16, color='black')
        #imgrid[i].tick_params(axis='x', color='white')
        imgrid[i].axis["bottom"].label.set_text(r"$\delta m$")
        imgrid[i].axis["bottom"].label.set_size(20)

    if title == "":
        title = kgrid.filename
    plt.suptitle(title, size=24)

    return 0
def plot_heidke_skill_score(ds_d,
                            mod_names,
                            mod_longnames,
                            wet_thres,
                            months=None,
                            fpath_out=None):

    hss_ls = [
        validate_hss(ds_d[mod_name], ds_d.obs, wet_thres, months)
        for mod_name in mod_names
    ]

    lon = hss_ls[0].lon
    lat = hss_ls[0].lat

    buf = .5
    bbox = esd.cfg.bbox
    m = Basemap(resolution='i',
                projection='cyl',
                llcrnrlat=bbox[1] - buf,
                area_thresh=100000,
                urcrnrlat=bbox[-1] + buf,
                llcrnrlon=bbox[0] - buf,
                urcrnrlon=bbox[2] + buf)

    x_map, y_map = m(*np.meshgrid(lon, lat))

    axes_pad = .4
    cfig = plt.gcf()

    nrow = int(np.ceil(len(mod_names) / 3.0))
    grid = ImageGrid(cfig,
                     111,
                     nrows_ncols=(nrow, 3),
                     axes_pad=axes_pad,
                     cbar_mode="each",
                     cbar_pad=.1,
                     cbar_location="bottom",
                     cbar_size='4%')

    levels = get_levels(np.concatenate(
        [a_correl.values.ravel() for a_correl in hss_ls]),
                        diverging=False)

    #TODO: make dynamic
    lon_txt = 99.8
    lat_txt = 25.75
    x_txt, y_txt = m(lon_txt, lat_txt)

    def contour_da(da, i, title):

        m.ax = grid[i]
        cntr = m.contourf(x_map,
                          y_map,
                          da.values,
                          levels=levels,
                          cmap='viridis',
                          extend='both')
        cbar = plt.colorbar(cntr,
                            cax=grid.cbar_axes[i],
                            orientation='horizontal',
                            extend='both')
        cbar.ax.tick_params(labelsize=8)
        cbar.ax.set_xlabel('r', fontsize=8)
        m.drawcountries()
        m.drawcoastlines()
        m.ax.text(x_txt, y_txt, 'Mean: %.2f' % (da.mean(), ), fontsize=8)
        m.ax.text(x_txt + 2, y_txt, title, fontsize=8)
        #grid[i].set_title(title, fontsize=8)

    i = 0

    for a_correl, a_modname in zip(hss_ls, mod_longnames):
        contour_da(a_correl, i, a_modname)
        i += 1

    for j in np.arange(i, len(grid)):
        m.ax = grid[j]
        m.ax.axis('off')
        grid.cbar_axes[j].axis('off')

    for i in np.arange(len(mod_names)):
        cticks = grid.cbar_axes[i].get_xticklabels()
        cticks = np.array(cticks)
        cticks[np.arange(1, cticks.size, step=2)] = ''
        grid.cbar_axes[i].set_xticklabels(cticks)

    plt.suptitle('Heidke Skill Score (%.2f mm wet threshold)' % wet_thres)

    fig = plt.gcf()
    fig.set_size_inches(16.350, (11.52 / 2) * (nrow))  #w h
    plt.tight_layout()

    if fpath_out is not None:
        plt.savefig(fpath_out, dpi=150, bbox_inches='tight')

    return grid
Esempio n. 11
0
def compare_means_2d(manager_list,
                     start_date=None,
                     end_date=None,
                     months=list(range(1, 13)),
                     var_name="STFL",
                     level=-1,
                     level_kind=level_kinds.ARBITRARY,
                     out_img=None,
                     impose_min=None,
                     bounds=None):
    """
    Plots a panel of plots for each run
    """

    ncols = 2
    nrows = len(manager_list) // ncols + 1

    # gs = gridspec.GridSpec(nrows, ncols, top=0.985, right=0.985, hspace=0.2, left = 0.01)

    fig = plt.figure()

    vmin = np.Infinity
    vmax = -np.Infinity
    quadMesh = None
    run_id_to_field = {}
    run_id_to_x = {}
    run_id_to_y = {}
    run_id_to_basemap = {}
    run_id_to_manager = {}
    for i, theManager in enumerate(manager_list):
        assert isinstance(theManager, Crcm5ModelDataManager)
        data_field = theManager.get_mean_field(start_date.year,
                                               end_date.year,
                                               months=months,
                                               var_name=var_name,
                                               level=level,
                                               level_kind=level_kind)

        theId = theManager.run_id

        run_id_to_field[theId] = data_field
        run_id_to_manager[theId] = theManager
        run_id_to_basemap[theId] = theManager.get_omerc_basemap()
        b = run_id_to_basemap[theId]
        x, y = b(theManager.lons2D, theManager.lats2D)
        run_id_to_x[theId] = x
        run_id_to_y[theId] = y

        vmax = max(np.max(data_field), vmax)
        vmin = min(np.min(data_field), vmin)

    if impose_min is not None:
        vmin = impose_min

    print(vmin, vmax)

    cmap = my_colormaps.get_lighter_jet_cmap(ncolors=15)

    dcol = (vmax - vmin) / float(cmap.N)
    if bounds is None:
        bounds = [vmin + i * dcol for i in range(cmap.N + 1)]

    if vmin * vmax < 0:
        bounds.append(0)
    bounds = list(sorted(bounds))

    norm = BoundaryNorm(bounds, len(bounds))

    imgGrid = ImageGrid(fig,
                        111,
                        nrows_ncols=(nrows, ncols),
                        axes_pad=0.5,
                        cbar_size="5%",
                        cbar_pad="5%",
                        share_all=True)

    i = 0
    for theId, data_field in run_id_to_field.items():
        ax = imgGrid[i]  # fig.add_subplot(gs[i // ncols, i % ncols])
        ax.set_title(theId)
        b = run_id_to_basemap[theId]
        x = run_id_to_x[theId]
        y = run_id_to_y[theId]

        theManager = run_id_to_manager[theId]
        assert isinstance(theManager, Crcm5ModelDataManager)
        if hasattr(theManager, "slope"):
            data_field = np.ma.masked_where(theManager.slope < 0, data_field)

        quadMesh = b.pcolormesh(x,
                                y,
                                data_field,
                                vmin=vmin,
                                vmax=vmax,
                                cmap=cmap,
                                ax=ax,
                                norm=norm)
        b.drawcoastlines(ax=ax)
        i += 1

    assert isinstance(fig, Figure)

    # ax = fig.add_subplot(gs[i // ncols, i % ncols])
    # assert isinstance(ax, Axes)
    #ax.set_aspect(20)
    #ax.set_anchor("W")

    cax = imgGrid.cbar_axes[len(run_id_to_field) - 1]
    cax.colorbar(quadMesh, ticks=bounds, format="%.3g")

    # fig.colorbar(quadMesh, cax = ax, ticks = bounds, format = "%.2g")
    if out_img is None:
        fig.savefig("_".join(map(str, months)) + "_2d_means.png")
    else:
        fig.savefig(out_img)
    pass
Esempio n. 12
0
plt.rc('figure', titlesize=BIGGER_SIZE,
       figsize=(20, 20))  # fontsize of the figure title
plt.rc('lines', linewidth=10, markersize=25)

#  dat = np.load('data/histograms_idrid_data/IDRiD_39-MA-Illuminate_Sharpen.npz')
#  h = dat['healthy']
#  d = dat['diseased']
#  hs = (h/h.sum()).cumsum()
#  ds = (d/d.sum()).cumsum()

img_id = 'IDRiD_03'
im = plt.imread(
    f'data/IDRiD_segmentation/1. Original Images/a. Training Set/{img_id}.jpg')
im2 = competing_methods.illuminate_sharpen(
    im, focus_region=util.get_foreground(im))
fig, axs = plt.subplots(1, 2, figsize=(8, 4))
fig = plt.figure(figsize=(20, 20))
axs = ImageGrid(fig, 111, (1, 2), share_all=True)
axs[0].get_yaxis().set_ticks([])
axs[0].get_xaxis().set_ticks([])
axs[0].imshow(im)
axs[1].imshow(im2)  # TODO
fig.savefig(f'./paper_plot_fig1_{img_id}.png', bbox_inches='tight')
fig, ax = plt.subplots(figsize=(20, 20))
ax.imshow(im2)
ax.axis('off')
fig.savefig(f'{img_id}_illuminate_sharpen.png', bbox_inches="tight")
ax.imshow(im)
ax.axis('off')
fig.savefig(f'{img_id}.png', bbox_inches='tight')
Esempio n. 13
0
#from pywcsgrid2.axes_wcs import AxesWcs, GridHelperWcs
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset
import mpl_toolkits.axisartist as axisartist
import matplotlib.patheffects as patheffects

if 1:

    f = pyfits.open("pspc_skyview.fits")
    d = f[0].data
    h = f[0].header

    fig = plt.figure(1)

    grid = ImageGrid(fig, (1, 1, 1),
                     nrows_ncols=(1, 1),
                     cbar_mode="single",
                     cbar_pad="2%",
                     cbar_location="right",
                     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")
Esempio n. 14
0
def plot_slices(slc, cutax='x'):
    fields = [
        'nH', 'temperature', 'velocity_z', 'Z', 'specific_scalar3',
        'ram_pok_z', 'pok', 'mag_pok'
    ]
    nologs = ['specific_scalar0', 'Z', 'velocity_z', 'beta']
    whites = [
    ]  #'nH','temperature','velocity_z','Z','specific_scalar3','magnetic_field_strength']

    nf = len(fields)
    fig = plt.figure(figsize=(2 * nf, 8), num=0)
    g = ImageGrid(fig, [0.05, 0.1, 0.85, 0.75], (1, nf),
                  label_mode='all',
                  aspect=True,
                  axes_pad=0.)

    for i, f in enumerate(fields):
        ax = g[i]
        plt.sca(ax)
        if f == 'Z':
            data = slc[cutax]['specific_scalar0'] / 0.02
        elif f == 'beta':
            data = slc[cutax]['pok'] / slc[cutax]['mag_pok']
        elif f == 'betainv':
            data = slc[cutax]['mag_pok'] / slc[cutax]['pok']
        else:
            data = slc[cutax][f]
        if not (f in nologs):
            data = np.log10(data)
#         print(f,data.min(),data.max())

        im = plt.imshow(data, extent=slc['yextent'], origin='lower')
        if f in norms:
            im.set_norm(norms[f])
        if f in cmaps:
            im.set_cmap(cmaps[f])

        plt.ylim(-0.5, 3.5)
        cax = inset_axes(ax,
                         '75%',
                         '4%',
                         loc='upper center',
                         bbox_to_anchor=[0., 0., 1., 1.1],
                         bbox_transform=ax.transAxes)

        #         cax = inset_axes(ax,'75%','4%',loc='lower center',
        #                          bbox_to_anchor=[0.,0.,1.,1],
        #                          bbox_transform=ax.transAxes)
        cbar = plt.colorbar(cax=cax, orientation='horizontal')
        cbar.minorticks_off()
        cbar.ax.xaxis.set_label_position('top')
        if f == 'Z':
            cbar.set_ticks(ticker.FixedLocator([1 / 3, 1, 3]))
            cbar.ax.set_xticklabels(['1/3', '1', '3'])
        elif f == 'nH':
            cbar.set_ticks(ticker.FixedLocator([-5, -3, -1, 1]))
        elif f == 'specific_scalar3':
            cbar.set_ticks(ticker.FixedLocator([-3, -2, -1, 0]))
        elif f == 'temperature':
            cbar.set_ticks(ticker.FixedLocator([2, 4, 6, 8]))
        elif 'pok' in f:
            cbar.set_ticks(ticker.FixedLocator([2, 4, 6]))
        elif 'velocity_z' in f:
            cbar.set_ticks([-1.e3, -1e2, 1e2, 1.e3])
        elif f == 'magnetic_field_strength':
            cbar.set_ticks(ticker.FixedLocator([-2, -1, 0, 1, 2]))

        if f in labels:
            label = labels[f]
            if not (f in nologs):
                label = r'$\log($' + label + r'$)$'
            cbar.set_label(label, va='bottom')


#         cbar.ax.xaxis.tick_top()
        if (f in whites):
            set_axis_color(cbar.ax, 'xy', 'w')
            cbar.outline.set_edgecolor('w')

    plt.setp([ax.get_yticklabels() for ax in g[1:-1]], visible=False)
    plt.setp([ax.get_xticklabels() for ax in g[1:-1]], visible=False)

    ax = g[0]
    ax.set_ylabel('z [kpc]')
    ax.set_xlabel('y [kpc]')
    #     ax.xaxis.tick_top()
    #     ax.xaxis.set_label_position('top')
    ax = g[-1]
    ax.set_ylabel('z [kpc]')
    ax.set_xlabel('y [kpc]')
    ax.yaxis.tick_right()
    ax.yaxis.set_label_position('right')

    for ax in g:
        ax.tick_params(axis='y', which='both', direction='inout')
        ax.tick_params(which='major', size=8)
        ax.tick_params(which='minor', size=4)
    return fig
Esempio n. 15
0
if (condition == 'gauss'):
    #f = plt.figure(figsize= (5,11))
    f = plt.figure(figsize=(6, 8))
    to_Plot = [49, 199] * 3
    folders = ['_nocol', '_tau10000', '_tau500']
    ylabels = ['Collisionless', '$\\tau =$ $10000$', '$\\tau =$ $500$']
    colormap = plt.cm.Reds
    #      colormap.set_under(color = 'white')
    colormap.set_bad(color='black')
    from mpl_toolkits.axes_grid1.axes_grid import ImageGrid
    ax = ImageGrid(f,
                   111,
                   nrows_ncols=(2, 3),
                   axes_pad=0.2,
                   cbar_mode='single',
                   cbar_pad=0.1,
                   share_all=True,
                   aspect=True,
                   direction='column')

    #      ax[0].set_title(r"t = 5")
    #      ax[4].set_title(r"t = 20")
    ax[0].set_ylabel(r"t = 5")
    ax[1].set_ylabel(r"t = 20")

    #      ax[0].set_aspect(0.5)
    #      ax[1].set_aspect(0.5)
    #      ax[2].set_aspect(0.5)
    #      ax[3].set_aspect(0.5)
Esempio n. 16
0
def plot_validation_grid_maps(ds, err_metrics, bbox):
     
    lon = ds.lon
    lat = ds.lat
 
    buf = .5
    m = Basemap(resolution='i',projection='cyl', llcrnrlat=bbox[1]-buf,
                area_thresh=100000, urcrnrlat=bbox[-1]+buf,
                llcrnrlon=bbox[0]-buf, urcrnrlon=bbox[2]+buf)
     
    x_map, y_map = m(*np.meshgrid(lon,lat))
     
    axes_pad = .2
    cfig = plt.gcf()
    grid = ImageGrid(cfig,111,nrows_ncols=(1 + ds.mod_name.size, 1 + len(err_metrics)),
                     axes_pad=axes_pad, cbar_mode="each", cbar_pad=.1, cbar_location="bottom",
                     cbar_size='4%')
     
    def contour_a(a, diverging=True, levels=None):
         
        if levels is None:
            levels = get_levels(a, diverging)
             
        if diverging:
            cmap = 'RdBu_r'
        else:
            cmap = 'viridis'
         
        cntr = m.contourf(x_map,y_map,a,levels=levels, cmap=cmap, extend='both')
        return cntr
         
    levels_vals = get_levels(np.concatenate([ds.obs.values.ravel(), ds.mod.values.ravel()]), diverging=False)
    levels_err = {err_name:get_levels(ds[err_name].values.ravel(), diverging=True) for err_name in err_metrics}
    
    #TODO: make dynamic     
    lon_txt = 99.8
    lat_txt = 25.75
    x_txt,y_txt = m(lon_txt, lat_txt)
     
    def plot_a_model(mod_name, i):
         
        m.ax = grid[i]
        cntr = contour_a(ds.mod.loc[mod_name].values,diverging=False,levels=levels_vals)
        cbar = plt.colorbar(cntr, cax = grid.cbar_axes[i],orientation='horizontal',extend='both')
        cbar.ax.tick_params(labelsize=8) 
        m.drawcountries()
        m.drawcoastlines()
        m.ax.text(x_txt,y_txt,'Mean: %.2f'%(ds.mod.loc[mod_name].mean(),),fontsize=8)
        
        for j,err_name in enumerate(err_metrics):
            
            m.ax = grid[i+j+1]
            cntr = contour_a(ds[err_name].loc[mod_name].values, levels=levels_err[err_name])
            cbar = plt.colorbar(cntr, cax = grid.cbar_axes[i+j+1],orientation='horizontal',extend='both')
            cbar.ax.tick_params(labelsize=8) 
            m.drawcountries()
            m.drawcoastlines()
            m.ax.text(x_txt,y_txt,'MAE: %.2f  Mean: %.2f'%(np.abs(ds[err_name].loc[mod_name]).mean(),
                                                           ds[err_name].loc[mod_name].mean()),fontsize=8)
                 
    m.ax = grid[0]
    cntr = contour_a(ds.obs.values,diverging=False,levels=levels_vals)
    cbar = plt.colorbar(cntr, cax = grid.cbar_axes[0],orientation='horizontal',extend='both')
    cbar.ax.tick_params(labelsize=8)
    x,y = m(lon_txt, lat_txt)
    m.ax.text(x,y,'Mean: %.2f'%(ds.obs.mean(),),fontsize=8) 
    m.drawcountries()
    m.drawcoastlines()
    
    for j,err_name in enumerate(err_metrics):
    
        m.ax = grid[j+1]
        m.ax.axis('off')
        grid.cbar_axes[j+1].axis('off')
             
    nplot = len(err_metrics) + 1
    
    for mod_name in ds.mod_name.values:
        
        plot_a_model(mod_name, nplot)
        nplot = nplot + len(err_metrics) + 1
     
    # Set titles
    grid[0].set_title(ds.obs.longname, fontsize=8)
    nplot = len(err_metrics) + 2
    for j,err_name in enumerate(err_metrics):
        grid[nplot+j].set_title(ds[err_name].longname, fontsize=8)
     
    # Set y labels
    grid[0].set_ylabel('Observed',fontsize=8)
    nplot = len(err_metrics) + 1
    for mod_name in ds.mod_name.values:
        grid[nplot].set_ylabel(mod_name,fontsize=8)
        nplot = nplot + len(err_metrics) + 1
    
    return grid