def show_reduction_pct(self, locations=None, site_labels=None):
     """ locations: list of Location objects
         site_labels ("fraction" | "names"): switch to turn on labeling of the markers of the sites specified by argument locations.  If "fraction", sites are labeled with their fractional precipitation reduction; if "names", they are labeled with teh location name.
     """
     frac = self.get_IDE_reduction()
     cmap, norm = colormap_nlevs.setup_colormap(0.0,
                                                1.0,
                                                nlevs=11,
                                                cmap=plt.get_cmap('YlGnBu'),
                                                extend='neither')
     wcm = WorldCalMap()
     wcm.plot(frac,
              self.dlon,
              self.dlat,
              vmin=0.0,
              vmax=1.0,
              midpoint=0.5,
              bands_above=6,
              bands_below=6,
              extend='neither',
              locations=locations,
              cbar_tstr=((u'drought simulation precipitation as fraction '
                          u'of 1948\u20132004 annual mean precipitation')),
              site_labels="names")
     wcm.crop_save(
         os.path.join(
             os.getenv('HOME'), 'plots', 'maptest',
             'IDE_pct_map_interp{}.png'.format(
                 self.lat.size != self.dlat.size)))
     plt.close(wcm.fig)
Beispiel #2
0
    def map_nearest_noaa_site(self):
        """Plot the top boundary using
        stem_pytools.STEM_mapper.Mapper124x124, and save the map to
        ./top_bnd.pdf
        """
        stem_lon = self.d.get_lon()
        stem_lat = self.d.get_lat()

        top_cmap, top_norm = colormap_nlevs.setup_colormap(
            np.floor(self.top_bnd.min()),
            np.ceil(self.top_bnd.max()),
            nlevs=6,
            cmap=plt.get_cmap('Oranges'),
            extend='neither')

        m = STEM_mapper.Mapper124x124(self.top_bnd).draw_map(
            fast_or_pretty='pretty',
            cmap=top_cmap,
            norm=top_norm,
            t_str='',
            cbar_fmt_str='%d')
        m.map.fig.set_figheight(8)
        m.map.fig.set_figwidth(8)

        sites_col = "#1b9e77"  # http://colorbrewer2.org dark2[1]
        fontsz = 14
        for this_site in np.unique(self.nearest_site_array):
            idx = np.where(self.sites_summary.site_code == this_site)[0][0]
            this_x, this_y = m.map.map(self.sites_summary.longitude[idx],
                                       self.sites_summary.latitude[idx])
            m.map.ax_map.text(this_x,
                              this_y,
                              this_site,
                              fontsize=fontsz,
                              color=sites_col,
                              horizontalalignment='center',
                              verticalalignment='center')
        # draw bounds between NOAA sites' regions of top bound
        vals = np.unique(self.top_bnd)
        levs = vals[0:-1] + (np.diff(vals) / 2.0)
        m.map.map.contour(stem_lon, stem_lat, self.top_bnd,
                          levels=levs, latlon=True, colors=sites_col)

        # plot lateral bounds cell indices on map
        lat_bounds_col = "#7570b3"  # http://colorbrewer2.org dark2[2]
        lat = domain.get_2d_perimeter(d.get_lat())
        lon = domain.get_2d_perimeter(d.get_lon())
        x, y = m.map.map(lon, lat)
        for i in (0, 62, 186, 330, 434):
            m.map.ax_map.text(x[i], y[i],  str(i),
                              color="black",
                              size=fontsz,
                              bbox={"color": "black", "facecolor": "white"})

        # label the color bar
        m.map.ax_cmap.set_title('[COS] (ppt)\n',
                                fontdict={'fontsize': fontsz})
        m.map.ax_cmap.tick_params(labelsize=fontsz)
        m.map.fig.savefig('top_bnd.pdf')
    def __set_cmap_norm(self):
        """get colormap, normalizer

        """
        self.cmap, self.norm = colormap_nlevs.setup_colormap(
            vmin=self.vmin,
            vmax=self.vmax,
            nlevs=self.ncolorlevs,
            cmap=self.base_colormap,
            extend='neither')
def plot_landuse(ax, lon, lat, data):
    cmap, norm = setup_colormap(
        0,
        21,
        nlevs=21,
        cmap=get_IGBP_modMODIS_21Category_PFTs_cmap())
    cm = ax.pcolormesh(lon,
                       lat,
                       data,
                       cmap=cmap,
                       norm=norm)
    ax.set_extent((lon.min(), lon.max(),
                   lat.min(), lat.max()))
    ax.coastlines(resolution='10m', color='black')
    return(cm)
nha_x = 33
nha_y = 70

cma_x = 29
cma_y = 60

sca_x = 23
sca_y = 44

molecules_m3_to_ppt = 1e12
cos_sca = cos_clim['data'][:, :, sca_x, sca_y] * molecules_m3_to_ppt

cmap, norm = colormap_nlevs.setup_colormap(vmin=cos_sca.min() - 1,
                                           vmax=cos_sca.max() + 1,
                                           nlevs=20,
                                           cmap=plt.get_cmap('Blues'),
                                           extend='neither')

fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(15, 8))
cm = ax.pcolormesh(np.transpose(cos_sca), cmap=cmap, norm=norm,
                   linewidth=0, rasterized=True)
ax.set_xlim([0, 1488])
ax.set_ylim([0, 22])
ax.set_ylabel('STEM Z level')
ax.set_xlabel('hours since 1 July 2008 00:00')
ax.set_title('SCA [COS], climatological bounds STEM run')
ax_cb = plt.colorbar(cm, cmap=cmap, norm=norm, ax=ax)
ax_cb.set_label('[COS] (ppt)')
ax_cb.solids.set_rasterized(True)
fig.savefig('/global/homes/t/twhilton/plots/SCA_COS.png')
Beispiel #6
0
    def add_ocs_contour_plot(self,
                             lons,
                             lats,
                             data,
                             t_str=None,
                             vmax=None,
                             vmin=None,
                             n_levs=20,
                             cmap=cm.get_cmap('Blues'),
                             extend='neither',
                             cbar_t_str=None,
                             colorbar_args={},
                             plotfunc=None):
        """Draw filled contours of the specified OCS data over the
        map.

        INPUT PARMATERS:
        lons: MxN numpy array of longitudes
        lats: MxN numpy array of latitudes
        data: MxN numpy array of data to be contoured
        t_str: title string for the map axes
        vmax: maximum value for color scale.  Default is data.max()
        vmin: minimum value for color scale.  Default is data.min()
        n_levs: number of contour levels.  Default is 20.
        cmap: color map to use for contours.  e.g. cm.get_cmap('Blues').  See
           http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps.
        extend: one of [ 'neither' | 'both' | 'min' | 'max' ], and is
           passed to matplotlib.pyplot.contourf via the 'extend' keyword.
        cbar_t_str: title string for colorbar
        colorbar_args: dict; additional keyword arguments to be passed
            to matplotlib.pypolt.colorbar
        plotfunc: {basemap.Basemap.pcolor} |
            basemap.Basemap.pcolormesh | basemap.Basemap.contourf:
            function to produce the contour plot.
        """

        if vmin is None:
            vmin = data.min()
        if vmax is None:
            vmax = data.max()

        cmap, norm = colormap_nlevs.setup_colormap(vmin=vmin,
                                                   vmax=vmax,
                                                   nlevs=n_levs,
                                                   cmap=cmap,
                                                   extend=extend)
        if plotfunc is None:
            plotfunc = self.map.pcolor
        cs = plotfunc(lons,
                      lats,
                      data,
                      ax=self.ax_map,
                      latlon=True,
                      cmap=cmap,
                      vmin=vmin,
                      vmax=vmax,
                      norm=norm)

        if self.ax_cmap is not None:
            # plot a color legend
            plt.colorbar(mappable=cs,
                         cax=self.ax_cmap,
                         cmap=cmap,
                         norm=norm,
                         **colorbar_args)
            if cbar_t_str is not None:
                self.ax_cmap.set_title(cbar_t_str)

        if t_str is not None:
            # place a time label at (140, 20N) (out in the Pacific
            # Ocean west of Mexico)
            t_lab_lon = -140
            t_lab_lat = 20
            # t_str = datetime.strftime( t_str, '%d %B %Y %H:%M' )
            self.ax_map.text(*self.map(t_lab_lon, t_lab_lat),
                             s=t_str,
                             bbox=dict(facecolor='white', alpha=0.5))

        # self.draw_mw_box()
        return(cs)
def draw_all_panels(cos, gpp, fCOS, models=None, models_str=None):

    if models is None:
        models = ['MPI_161',
                  'canibis_161',
                  'kettle_161',
                  'casa_m15_161',
                  'casa_gfed_161',
                  'casa_gfed_135',
                  'casa_gfed_187']
    if models_str is None:
        models_str = ['MPI',
                      'Can-IBIS',
                      'Kettle',
                      'CASA-m15',
                      'CASA-GFED3',
                      'CASA-GFED3',
                      'CASA-GFED3']

    gpp_vmin = 0.0
    gpp_vmax = np.percentile(np.dstack([gpp[k] for k in models]).flatten(), 99)
    #gpp_vmax = 0.45  # np.dstack([GPP[k] for k in models]).flatten().max()
    fcos_vmin = 0.0  # np.dstack([fCOS[k] for k in models]).flatten().min()
    # fcos_vmax = np.percentile(np.dstack([fCOS[k] for k in models]).flatten(), 99)
    fcos_vmax = np.dstack([fCOS[k] for k in models]).flatten().max()
    cos_vmin = 0.0
    cos_vmax = np.dstack([cos[k] for k in models]).flatten().max()
    # cos_vmax = np.percentile(np.dstack([cos[k] for k in models]).flatten(), 99)
    # cos_vmax = 80

    print('ceil(max): {}'.format(
        np.ceil(np.dstack([cos[k] for k in models]).flatten().max())))

    fig, ax, cbar_ax = setup_panel_array(nrows=3, ncols=len(models))
    map_objs = np.empty(ax.shape, dtype='object')

    gpp_cmap, gpp_norm = colormap_nlevs.setup_colormap(
        gpp_vmin, gpp_vmax,
        nlevs=20,
        cmap=plt.get_cmap('Greens'),
        extend='max')

    color_band_edges = [0.0, 3.5, 6.5, 12.0, 13.0]
    color_band_edges = [0.0, 3.25, 6.5, 9.75, 13.0]
    gpp_base_cmap = plt.cm.Greens(np.linspace(0.05,
                                              0.95,
                                              len(color_band_edges * 10)))
    gpp_base_cmap_small = plt.cm.Greens(np.linspace(0.05,
                                                    0.95,
                                                    len(color_band_edges)))
    gpp_base_cmap = gpp_base_cmap[[0, 10, 40, 45, 49], :]
    print 'gpp_base_cmap ', gpp_base_cmap
    print 'gpp_base_cmap_small ', gpp_base_cmap_small
    gpp_cmap, gpp_norm = from_levels_and_colors(color_band_edges,
                                                gpp_base_cmap_small,
                                                extend='max')

    mod_objs = ndp.get_runs()
    for i, this_mod in enumerate(models):
        if np.mod(i, 2) == 0:
            # the GPP maps are duplicates within each GPP model, so
            # only plot every other one
            # plot GPP drawdown maps
            print("plotting {model}({k}) GPP".format(model=models_str[i],
                                                     k=models[i]))

            map_objs[0, i], cm = draw_map(
                t_str='{}, LRU={}'.format(models_str[i],
                                          mod_objs[this_mod].LRU),
                ax=ax[0, i],   # axis 0 is left-most on row 3
                data=gpp[this_mod],
                vmin=gpp_vmin,
                vmax=gpp_vmax,
                cmap=gpp_cmap,
                norm=gpp_norm)
        else:
            fig.delaxes(ax[0, i])
    all_gpp = np.dstack([v for v in gpp.values()]).flatten()
    cb = colorbar_from_cmap_norm(gpp_cmap,
                                 gpp_norm,
                                 cbar_ax[0, 0],
                                 '%0.2f',
                                 all_gpp)
    t = cbar_ax[0, 0].set_title('GPP ($\mu$mol C m$^{-2}$ s$^{-1}$)\n')
    t.set_y(1.09)
    t.set_fontsize(20)

    fcos_cmap, fcos_norm = colormap_nlevs.setup_colormap(
        fcos_vmin, fcos_vmax,
        nlevs=6,
        cmap=plt.get_cmap('Blues'),
        extend='neither')
    for i, this_mod in enumerate(models):
        # plot fCOS drawdown maps
        print("plotting {model}({k}) fCOS".format(model=models_str[i],
                                                 k=models[i]))
        map_objs[1, i], cm = draw_map(t_str=None,
                                      ax=ax[1, i],
                                      data=fCOS[this_mod],
                                      vmin=fcos_vmin,
                                      vmax=fcos_vmax,
                                      cmap=fcos_cmap,
                                      norm=fcos_norm)
    all_fcos = np.dstack([v for v in fCOS.values()]).flatten()
    cb = colorbar_from_cmap_norm(fcos_cmap,
                                 fcos_norm,
                                 cbar_ax[1, 0],
                                 '%d',
                                 all_fcos)
    t = cbar_ax[1, 0].set_title('$F_{plant}$ (pmol COS m$^{-2}$ s$^{-1})$')
    t.set_y(1.09)
    t.set_fontsize(20)

    cos_cmap, cos_norm = colormap_nlevs.setup_colormap(
        cos_vmin,
        cos_vmax,
        nlevs=7,
        cmap=plt.get_cmap('Oranges'),
        extend='max')
    for i, this_mod in enumerate(models):
        # plot [COS] drawdown maps
        print("plotting {model}({k}) COS DD".format(model=models_str[i],
                                                 k=models[i]))
        this_cos = cos[this_mod]
        if any(this_cos.flatten() < 0):
            warnings.warn('COS drawdown values < 0.0 set to 0.0')
            this_cos[this_cos < 0] = 0
        map_objs[2, i], cm = draw_map(t_str=None,
                                      ax=ax[2, i],
                                      data=this_cos,
                                      vmin=cos_vmin,
                                      vmax=cos_vmax,
                                      cmap=cos_cmap,
                                      norm=cos_norm)

        all_dd = np.dstack([v for v in cos.values()]).flatten()
    cb = colorbar_from_cmap_norm(cos_cmap,
                                 cos_norm,
                                 cbar_ax[2, 0],
                                 '%d',
                                 all_dd)
    t = cbar_ax[2, 0].set_title('STEM [COS] drawdown (ppt)')
    t.set_y(1.09)
    t.set_fontsize(20)
    # fig.tight_layout()
    return(fig, map_objs, cos_cmap, cos_norm)
Beispiel #8
0
nha_x = 33
nha_y = 70

cma_x = 29
cma_y = 60

sca_x = 23
sca_y = 44

molecules_m3_to_ppt = 1e12
cos_sca = cos_clim['data'][:, :, sca_x, sca_y] * molecules_m3_to_ppt

cmap, norm = colormap_nlevs.setup_colormap(vmin=cos_sca.min() - 1,
                                           vmax=cos_sca.max() + 1,
                                           nlevs=20,
                                           cmap=plt.get_cmap('Blues'),
                                           extend='neither')

fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(15, 8))
cm = ax.pcolormesh(np.transpose(cos_sca),
                   cmap=cmap,
                   norm=norm,
                   linewidth=0,
                   rasterized=True)
ax.set_xlim([0, 1488])
ax.set_ylim([0, 22])
ax.set_ylabel('STEM Z level')
ax.set_xlabel('hours since 1 July 2008 00:00')
ax.set_title('SCA [COS], climatological bounds STEM run')
ax_cb = plt.colorbar(cm, cmap=cmap, norm=norm, ax=ax)
    years = [1972, 1972]
    months = [1, 2]
    fnames = [
        os.path.join(qian_dir,
                     'clmforc.Qian.c2006.T62.Prec.{}-{:02d}.nc'.format(y, m))
        for y in years for m in months
    ]

    pcp = [qpm.QianMonthlyPCPData(f, 'PRECTmms') for f in fnames]
    for this_pcp in pcp:
        print "parsing {}".format(os.path.basename(this_pcp.fname))
        this_pcp.read_nc()

    fig, ax = plt.subplots(nrows=len(years), ncols=1)
    for y, m, this_pcp, this_ax in zip(itertools.cycle(years), months, pcp,
                                       list(ax)):
        this_m = qpm.setup_worldmap(this_ax)
        cmap, norm = colormap_nlevs.setup_colormap(0.0,
                                                   0.0053803,
                                                   nlevs=11,
                                                   cmap=plt.get_cmap('Blues'),
                                                   extend='neither')
        this_m.pcolormesh(this_pcp.lon,
                          this_pcp.lat,
                          this_pcp.data_all[0, ...],
                          latlon=True)
        this_ax.annotate("{} {} pcp".format(y, m),
                         xy=(0, 1),
                         xycoords='axes fraction')
    fig.savefig(os.path.join(os.getenv('CSCRATCH'), 'qian_pcp.png'))