def plt_spatial_seasonal_mean(variable, variable_id, add_colorbar=None, title=None):
    fig, axsm = plt.subplots(
        2, 2, figsize=[10, 7], subplot_kw={"projection": ccrs.PlateCarree()}
    )
    fig.suptitle(title, fontsize=16, fontweight="bold")
    axs = axsm.flatten()
    for ax, i in zip(axs, variable.season):
        im = variable.sel(season=i,).plot.contourf(
            ax=ax,
            transform=ccrs.PlateCarree(),
            cmap=cm.devon_r,
            robust=True,
            vmin=plt_dict[variable_id][plt_dict["header"].index("vmin")],
            vmax=plt_dict[variable_id][plt_dict["header"].index("vmax")],
            levels=plt_dict[variable_id][plt_dict["header"].index("levels")],
            extend="max",
            add_colorbar=add_colorbar,
        )

        ax.coastlines()
        gl = ax.gridlines()
        ax.add_feature(cy.feature.BORDERS)
        gl.top_labels = False
        ax.set_title("season: {}".format(i.values))

    plt.tight_layout()
    fig.subplots_adjust(top=0.88)

    return (
        fig,
        axs,
        im,
    )
예제 #2
0
def plt_twodhist_season(x,
                        y,
                        starty,
                        endy,
                        bins=None,
                        cmap=None,
                        range=None,
                        norm=None):
    """ Plots a two-dimensional histogram of variable x and y.
    
    Parameters:
    -----------
    x           : variable on x-axis
    y           : variable on y-axis
    starty      : string of analysis begin
    endy        : string of analysis end
    bisn        : None or int or [int, int] or array-like or [array, array]
    cmap        : Colormap or str
    range       : array-like shape(2, 2), optional,
    norm        : Normalize, optional
    """

    f, axs = plt.subplots(2, 2, figsize=[10, 10], sharex=True, sharey=True)

    for sea, ax in zip(
            x.groupby('time.season').sum('time').season, axs.flatten()):

        _pp = np.asarray(x.sel(time=(x['time.season'] == sea), ))
        _cl = np.asarray(y.sel(time=(y['time.season'] == sea), ))
        _p = _pp[~np.isnan(_pp)]
        _c = _cl[~np.isnan(_pp)]

        _p = _p[~np.isnan(_c)]
        _c = _c[~np.isnan(_c)]

        counts, xedges, yedges, im = ax.hist2d(
            _p,  #p.flatten(), # use .flatten to pass a (N,) shape array as requested by hist2d
            _c,  #l.flatten(), 
            #bins=(20,50),
            bins=bins,
            density=False,
            #     density = True,  # If False, the default, returns the number of samples in each bin. If True, returns the probability density function at the bin, bin_count / sample_count / bin_area.
            cmap=cmap,
            range=range,
            cmin=0.5,
            norm=norm)
        ax.set_title(sea.values)
        ax.set_xlabel('Precipitation')
        ax.set_ylabel('Mass Fraction of Cloud Liquid + Ice Water')

    f.subplots_adjust(top=.85, right=0.8)
    f.suptitle('2D Histogram ' + starty + '-' + endy, fontweight='bold')
    #f.suptitle("Precipitation vs. Cloud Mass")
    cbar_ax = f.add_axes([1.01, 0.15, 0.025, 0.7])
    cbar = f.colorbar(im, cax=cbar_ax)
    cbar.ax.set_ylabel('Counts')
    ax.ticklabel_format(style='sci', axis='both', scilimits=(1, 0))

    plt.tight_layout()
def plt_scatter_iwp_sf_seasonal(
    ds, linreg, iteration, step, title=None, xlim=None, ylim=None
):

    fig, axsm = plt.subplots(
        2,
        2,
        figsize=[10, 7],
        sharex=True,
        sharey=True,
    )
    fig.suptitle(title, fontsize=16, fontweight="bold")

    axs = axsm.flatten()
    for ax, i in zip(axs, ds.season):
        ax.grid()
        for _lat, c in zip(iteration, cm.romaO(range(0, 256, int(256 / 4)))):
            # plot scatter
            ax.scatter(
                ds["iwp_{}_{}".format(_lat, _lat + step)].sel(season=i),
                ds["sf_{}_{}".format(_lat, _lat + step)].sel(season=i),
                label="{}, {}".format(_lat, _lat + step),
                color=c,
                alpha=0.5,
            )

            # plot regression line
            y = (
                np.linspace(0, 350)
                * linreg["slope_{}_{}".format(_lat, _lat + step)].sel(season=i).values
                + linreg["intercept_{}_{}".format(_lat, _lat + step)]
                .sel(season=i)
                .values
            )

            ax.plot(np.linspace(0, 350), y, color=c, linewidth="2")

        ax.set_ylabel("Snowfall (mm$\,$day$^{-1}$)", fontweight="bold")
        ax.set_xlabel("Ice Water Path (g$\,$m$^{-2}$)", fontweight="bold")
        ax.set_title(
            "season: {}; lat: ({}, {})".format(
                i.values, iteration[0], iteration[-1] + step
            )
        )
        ax.set_xlim(xlim)
        ax.set_ylim(ylim)

    axs[1].legend(
        loc="upper left",
        bbox_to_anchor=(1, 1),
        fontsize="small",
        fancybox=True,
    )

    plt.tight_layout()
def plt_bar_area_mean(
    ax,
    var_model,
    var_obs,
    loc,
    bar_width=None,
    hatch=None,
    alpha=None,
    label=None,
    ylabel=None,
):

    for k, c, pos in zip(
        var_model.model.values,
        cm.romaO(range(0, 256, int(256 / len(var_model.model.values)))),
        range(len(var_model.model.values)),
    ):
        ax.bar(
            pos + loc * bar_width,
            var_model.sel(model=k).values,
            color=c,
            width=bar_width,
            edgecolor="black",
            hatch=hatch,
            alpha=alpha,
        )

    ax.bar(
        len(var_model.model.values) + loc * bar_width,
        var_obs.values,
        color="k",
        width=bar_width,
        edgecolor="white",
        hatch=hatch,
        alpha=alpha,
        label=label,
    )

    ax.set_xticks(range(len(np.append((var_model.model.values), "ERA5").tolist())))
    ax.set_xticklabels(
        np.append((var_model.model.values), "ERA5").tolist(), fontsize=12, rotation=90
    )
    ax.set_ylabel(ylabel, fontweight="bold")

    ax.legend(
        loc="upper left",
        bbox_to_anchor=(1, 1),
        title="MEAN",
        fontsize="small",
        fancybox=True,
    )

    plt.tight_layout()
def plt_diff_seasonal(
    true_var, estimated_var, cbar_label, vmin=None, vmax=None, levels=None, title=None
):

    fig, axsm = plt.subplots(
        2, 2, figsize=[10, 7], subplot_kw={"projection": ccrs.PlateCarree()}
    )
    fig.suptitle(title, fontsize=16, fontweight="bold")

    axs = axsm.flatten()
    for ax, i in zip(axs, true_var.season):
        im = (
            (true_var - estimated_var)
            .sel(season=i)
            .plot.contourf(
                ax=ax,
                transform=ccrs.PlateCarree(),
                cmap=cm.bam,
                robust=True,
                add_colorbar=False,
                extend="both",
                vmin=vmin,
                vmax=vmax,
                levels=levels,
            )
        )
        # Plot cosmetics
        ax.coastlines()
        gl = ax.gridlines()
        ax.add_feature(cy.feature.BORDERS)
        gl.top_labels = False
        ax.set_title("season: {}".format(i.values))

    # colorbar
    fig.subplots_adjust(right=0.8)
    cbar_ax = fig.add_axes([1, 0.15, 0.025, 0.7])
    cb = fig.colorbar(im, cax=cbar_ax, orientation="vertical", fraction=0.046, pad=0.04)
    # set cbar label
    cb.set_label(label=cbar_label, weight="bold")

    plt.tight_layout()
    fig.subplots_adjust(top=1)

    return axs
예제 #6
0
def plt_mean_std_var_skew_kurt(var):
    """Plots the mean, standard deviation, variance, skewness and kurtosis for a given variable.
    
    Parameters:
    -----------
    var         : xarray variable to be plotted
    """
    f, axsm = sp_map(3, 2, figsize=[18, 8])
    axs = axsm.flatten()

    stat = ['Mean', 'Std', 'Variance', 'Skewness', 'Kurtosis']
    # Mean
    var.mean('time', keep_attrs=True).plot(ax=axs[0],
                                           transform=ccrs.PlateCarree(),
                                           robust=True)

    # STD
    var.std('time', keep_attrs=True).plot(ax=axs[1],
                                          transform=ccrs.PlateCarree(),
                                          robust=True)

    # Var
    var.var('time', keep_attrs=True).plot(ax=axs[2],
                                          transform=ccrs.PlateCarree(),
                                          robust=True)

    # skewness
    var.reduce(stats.skew, dim=('time'),
               keep_attrs=True).plot(ax=axs[3],
                                     transform=ccrs.PlateCarree(),
                                     robust=True)

    # kurtosis
    var.reduce(stats.kurtosis, dim=('time'),
               keep_attrs=True).plot(ax=axs[4],
                                     transform=ccrs.PlateCarree(),
                                     robust=True)

    axs[5].axis('off')
    for ax, i in zip(axs, range(len(stat))):
        ax.coastlines()
        ax.set_title(stat[i])

    plt.tight_layout()
예제 #7
0
def plt_stat_season(variable, stat, starty, endy):
    """Plots the seasonal statistics of the chosen statistic
    
    Parameters:
    -----------
    variable    : xarray variable to be plotted
    stat        : defines the statistics to plot,
                  must be: 'mean', 'st', 'var', 'skew', 'kur' 
    starty      : string of analysis begin
    endy        : string of analysis end
    """

    f, axsm = sp_map(2, 2, figsize=[18, 8])
    axs = axsm.flatten()

    for sea, ax in zip(
            variable.groupby('time.season').sum('time').season, axs.flatten()):
        if stat == 'mean':
            _title = 'Mean'
            im = variable.sel(time=(variable['time.season'] == sea), ).mean(
                'time', keep_attrs=True).plot(ax=ax,
                                              transform=ccrs.PlateCarree(),
                                              robust=True,
                                              add_colorbar=False)
        if stat == 'std':
            _title = 'Standard deviation'
            im = variable.sel(time=(variable['time.season'] == sea), ).std(
                'time', keep_attrs=True).plot(ax=ax,
                                              transform=ccrs.PlateCarree(),
                                              robust=True,
                                              add_colorbar=False)

        if stat == 'var':
            _title = 'Variance'
            im = variable.sel(time=(variable['time.season'] == sea), ).var(
                'time', keep_attrs=True).plot(ax=ax,
                                              transform=ccrs.PlateCarree(),
                                              robust=True,
                                              add_colorbar=False)
        if stat == 'skew':
            _title = 'Skewness'
            im = variable.sel(time=(variable['time.season'] == sea), ).reduce(
                stats.skew, dim=('time'),
                keep_attrs=True).plot(ax=ax,
                                      transform=ccrs.PlateCarree(),
                                      robust=True,
                                      add_colorbar=False)

        if stat == 'kur':
            _title = 'Kurtosis'
            im = variable.sel(time=(variable['time.season'] == sea), ).reduce(
                stats.kurtosis, dim=('time'),
                keep_attrs=True).plot(ax=ax,
                                      transform=ccrs.PlateCarree(),
                                      robust=True,
                                      add_colorbar=False)

        ax.coastlines()

    f.subplots_adjust(right=0.8, top=0.9)
    f.suptitle('%s %s - %s' % (_title, starty, endy), fontweight='bold')
    cbar_ax = f.add_axes([0.85, 0.15, 0.025, 0.7])
    f.colorbar(im, cax=cbar_ax, extend='both',
               format='%.0e').ax.set_ylabel(variable.attrs['long_name'] +
                                            ' [' + variable.attrs['units'] +
                                            ']')
    plt.tight_layout()
ax.set_title('Mean of 1990');

# There is obious higher values of CLW over China, Chile, Labrador See and around Svalbard in 1990. Lower values of CLW show in the tropics. High CLW values in China related to higher Aerosol content? High CLW because of the Andes?
# In 1991 Mt. Pinatubo errupted. I wonder how the CLW looks for 1991 and 1992.

# +
fig, axs = fct.sp_map(1,2, figsize=[18,8], sharex=True, sharey=True)

for yy, ax in zip(np.arange(1991,1993), axs.flatten()):
    im = fn['clw'].clw.sel(time = slice(str(yy)+'-01', str(yy)+'-12')).sum('lev',keep_attrs =  True).mean(['time'], keep_attrs = True).plot.pcolormesh(ax = ax, 
                                                transform = ccrs.PlateCarree(),
                                                )
    ax.coastlines()
    ax.set_title('Mean of %s' %yy)
    
plt.tight_layout()
# -

# Besides the different colorbar dimension one can not see a difference to 1990. The same areas have still high CLW. But I'm looking at model simulations, so that a model represents exactly a certain year is not very likely. One could say that the CLW is higher in 1992 (comparing the colorbar).
#
# Let's have a look on the decade.

f, ax = fct.sp_map(1, figsize = [8,5])
fn['clw'].clw.sel(time = slice('1990-01', '1999-12')).sum('lev',keep_attrs =  True).mean(['time'], keep_attrs = True).plot.pcolormesh(ax = ax, 
                                                transform = ccrs.PlateCarree(),
                                                )
ax.coastlines()
ax.set_title('Mean 1990-1999' );

# And now 30 years: