Пример #1
0
def plot_us_phenocam(ax, data, xlim, label, ylabel="", legend=False):

    from matplotlib.ticker import MultipleLocator

    minor_tick_interval = 10
    minorLocator = MultipleLocator(minor_tick_interval)

    ax.plot(data[0].times, data[0].data, c="peru", marker="o", ls=None)
    ax.plot(data[1].times, data[1].data, c="teal", marker="o", ls=None)

    ax.plot(data[2].times,
            data[2].data,
            c="peru",
            lw=2,
            ls="-",
            label=data[2].name)
    ax.plot(data[3].times,
            data[3].data,
            c="teal",
            lw=2,
            ls="-",
            label=data[3].name)

    if legend:
        ax.legend(loc="lower right",
                  frameon=False,
                  ncol=1,
                  fontsize=settings.FONTSIZE * 0.6)

    ax.xaxis.set_minor_locator(minorLocator)
    # turn of RHS y ticks
    ax.yaxis.set_ticks_position('left')
    ax.set_xlim(xlim)
    ax.set_ylim([0.28, 0.44])
    ax.set_ylabel(ylabel)
    ax.text(0.1, 0.8, label)

    utils.thicken_panel_border(ax)

    return  # plot_us_phenocam
Пример #2
0
def plot_modis_ts(axl, sos, sprt, dummy, label, anomalies, legend_loc):

    utils.plot_ts_panel(axl, [sos, dummy], "-", "phenological", loc=legend_loc)

    # make twin
    axr = axl.twinx()
    utils.plot_ts_panel(axr, [sprt], "-", "phenological", loc="")

    # prettify
    axl.set_ylim([-10, 10])
    axr.set_ylim([3, -3])

    # labels
    axl.text(0.02,
             0.83,
             label,
             transform=axl.transAxes,
             fontsize=settings.FONTSIZE * 0.8)
    axl.text(0.47, 0.88, anomalies[0], transform=axl.transAxes)
    axl.text(0.47, 0.78, anomalies[1], transform=axl.transAxes)

    # ticks etc
    minorLocator = MultipleLocator(1)
    for ax in [axl]:
        utils.thicken_panel_border(ax)
        ax.set_yticks(ax.get_yticks()[1:-1])
        ax.xaxis.set_minor_locator(minorLocator)

    for ax in [axr]:
        ax.yaxis.tick_right()
        utils.thicken_panel_border(ax)
        ax.set_yticks(ax.get_yticks()[1:-1])
        ax.xaxis.set_minor_locator(minorLocator)

    axl.set_xlim([1999, 2020])

    return  # plot_modis_ts
Пример #3
0
plt.xlim([1979.5, 2016.5])
ax.axhline(12, c='k', ls='-', lw=2, zorder=10)
ax.axhline(14, c='k', ls='-', lw=2, zorder=10)
ax.axhline(31, c='k', ls='-', lw=2, zorder=10)
ax.axhline(35, c='k', ls='-', lw=2, zorder=10)
ax.axhline(39, c='k', ls='-', lw=2, zorder=10)
ax.axhline(48, c='k', ls='-', lw=2, zorder=10)
plt.ylim([0, 48.1])

ax.set_yticks([6, 13, 22, 33, 37, 42])
ax.set_yticklabels(["NZ", "Asia", "Europe", "Great Lakes", "US", "Canada"])

minorLocator = MultipleLocator(1)
ax.xaxis.set_minor_locator(minorLocator)

utils.thicken_panel_border(ax)

plt.savefig(image_loc + "LKT_hovmuller{}".format(settings.OUTFMT))
plt.close()

#***************
# Figure 2

timeseries = read_ts(data_loc + "fig2a.csv")

trends = read_lakes(data_loc + "fig2c.csv")

anomalies = read_lakes(data_loc + "fig2b.csv")

# borrow from slp.py
fig = plt.figure(figsize=(8, 9))
Пример #4
0
def run_all_plots():

    #************************************************************************
    # Global Map
    if True:

        bounds = [-1000, -160, -120, -80, -40, 0, 40, 80, 120, 160, 1000]
        cube = read_map(DATALOC + "map")

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "GLE_{}_anoms".format(settings.YEAR), cube,
            settings.COLOURMAP_DICT["hydrological"], bounds,
            "Anomalies from 1981-2010 (mm year" + r'$^{-1}$' + ")")
        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "p2.1_GLE_{}_anoms".format(settings.YEAR),
            cube,
            settings.COLOURMAP_DICT["hydrological"],
            bounds,
            "Anomalies from 1981-2010 (mm year" + r'$^{-1}$' + ")",
            figtext="(s) Land Evaporation")

    # Evaporation Map
    if True:

        bounds = [-1000, -160, -120, -80, -40, 0, 40, 80, 120, 160, 1000]
        cube = read_map(DATALOC + "map_transp")

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "GLE_{}_transp".format(settings.YEAR), cube,
            settings.COLOURMAP_DICT["hydrological"], bounds,
            "Anomalies from 1981-2010 (mm year" + r'$^{-1}$' + ")")

    print("no other figures for {}'s report - author has made own".format(
        settings.YEAR))
    sys.exit()
    #************************************************************************
    # Timeseries figures
    if False:
        fig, ax1 = plt.subplots(figsize=(8, 5))

        globe, NH, SH, SOI = read_time(DATALOC + "timeseries")

        utils.plot_ts_panel(ax1, [globe, NH, SH],
                            "-",
                            "hydrological",
                            loc=LEGEND_LOC)

        for data in [globe, NH, SH]:
            slope, dummy, dummy = utils.median_pairwise_slopes(
                data.times, data.data, -99.9, 1.)

            fit_years, fit_values = utils.mpw_plot_points(
                slope, data.times, data.data)

            ax1.plot(fit_years, fit_values, c=settings.COLOURS["hydrological"][data.name], \
                         lw=2, ls="--")

        ax1.set_ylabel("Anomalies (mm year" + r'$^{-1}$' + ")",
                       fontsize=settings.FONTSIZE)
        ax1.set_ylim([-29, 29])

        for tick in ax1.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        ax2 = ax1.twinx()

        interpTimes = np.linspace(SOI.times[0], SOI.times[-1], 1000)
        interpData = np.interp(interpTimes, SOI.times, SOI.data)
        interpSOI = utils.Timeseries("SOI", interpTimes, interpData)

        ax2.fill_between(interpSOI.times, interpSOI.data, where=interpSOI.data >= 0, \
                             color='b', alpha=0.5, zorder=-1)
        ax2.fill_between(interpSOI.times, interpSOI.data, where=interpSOI.data <= 0, \
                             color='r', alpha=0.5, zorder=-1)

        ax2.set_xlim([1979, int(settings.YEAR) + 1])
        ax2.set_ylim([-5, 5])
        ax2.set_ylabel("SOI", fontsize=settings.FONTSIZE)

        for tick in ax1.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for tick in ax2.yaxis.get_major_ticks():
            tick.label2.set_fontsize(settings.FONTSIZE)

        utils.thicken_panel_border(ax2)

        plt.savefig(settings.IMAGELOC + "GLE_ts{}".format(settings.OUTFMT))

        plt.close()

    #************************************************************************
    # Hoemuller figure
    if False:
        bounds = [-100, -10, -8, -4, -2, 0, 2, 4, 8, 10, 100]
        times, latitudes, indata = read_hovmuller(DATALOC + "latitudinal")

        utils.plot_hovmuller(settings.IMAGELOC + "GLE_hovmuller", times, latitudes, indata, \
                             settings.COLOURMAP_DICT["hydrological"], bounds, \
                             "Anomaly (mm month"+r'$^{-1}$'+")")

    return  # run_all_plots
Пример #5
0
def run_all_plots():

    #************************************************************************
    # Precipitation Timeseries
    if False:

        ghcn, gpcc, gpcp, ghcn2, erai, merra2 = read_land(
            DATALOC + "Land_insitu_timeseries-1979.dat")

        fig = plt.figure(figsize=(8, 5))

        ax1 = plt.axes([0.1, 0.1, 0.85, 0.85])

        # Land
        utils.plot_ts_panel(ax1, [ghcn, gpcc, gpcp, ghcn2, erai, merra2],
                            "-",
                            "hydrological",
                            loc=LEGEND_LOC,
                            bbox=BBOX)

        ax1.set_ylim([-60, 100])
        ax1.yaxis.set_ticks([-50, -25, 0, 25, 50, 75, 100])
        ax1.set_ylabel("Anomaly (mm)", fontsize=settings.FONTSIZE)

        for tick in ax1.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for tick in ax1.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        # ax1.text(0.02, 0.9, "(a) Land in Situ", transform=ax1.transAxes, fontsize=settings.LABEL_FONTSIZE)

        plt.savefig(settings.IMAGELOC + "PCP_ts{}".format(settings.OUTFMT))
        plt.close()

    # old 3-panel plot for 2015 report
    if False:
        fig = plt.figure(figsize=(8, 8))

        ax1 = plt.axes([0.11, 0.68, 0.78, 0.3])
        ax2 = plt.axes([0.11, 0.38, 0.78, 0.3], sharex=ax1)
        ax3 = plt.axes([0.11, 0.08, 0.78, 0.3], sharex=ax1)

        # Land
        utils.plot_ts_panel(ax1, [ghcn, gpcc, gpcp, ghcn2, erai, merra2],
                            "-",
                            "hydrological",
                            loc=LEGEND_LOC,
                            bbox=BBOX)

        # Ocean
        ocean_year = read_domain(
            DATALOC + "gpcp_v23_globalocean_ann_1979_2018", "GPCP")

        o_clim, o_anoms = utils.calculate_climatology_and_anomalies_1d(
            ocean_year, 1981, 2010)

        ax2.plot(o_anoms.times,
                 o_anoms.data,
                 c="b",
                 ls="-",
                 label=o_anoms.name,
                 lw=2)

        # Nino and others
        land_year = read_domain(DATALOC + "gpcp_v23_globalland_ann_1979_2018",
                                "GPCP")
        l_clim, l_anoms = utils.calculate_climatology_and_anomalies_1d(
            land_year, 1981, 2010)
        combined_year = read_domain(
            DATALOC + "gpcp_v23_globallandocean_ann_1979_2018", "GPCP")
        c_clim, c_anoms = utils.calculate_climatology_and_anomalies_1d(
            combined_year, 1981, 2010)

        nino = read_domain(DATALOC + "nino34_1979_2018_ann_anomaly",
                           "Nino 3.4")

        ax3.plot(o_anoms.times,
                 o_anoms.data,
                 c="b",
                 ls="-",
                 label="{} Ocean".format(o_anoms.name),
                 lw=2,
                 zorder=10)
        ax3.plot(l_anoms.times,
                 l_anoms.data,
                 c="lime",
                 ls="-",
                 label="{} Land".format(l_anoms.name),
                 lw=2,
                 zorder=10)
        ax3.plot(c_anoms.times,
                 c_anoms.data,
                 c="r",
                 ls="-",
                 label="{} Land + Ocean".format(c_anoms.name),
                 lw=2,
                 zorder=10)
        ax3.plot([1960, 1961], [0, 0], c="k", label="Nino 3.4")

        ax4 = ax3.twinx()
        ax4.plot(nino.times, nino.data, c="k", zorder=1)
        ax4.fill_between(nino.times,
                         nino.data,
                         0,
                         color="0.5",
                         label=nino.name,
                         zorder=1)
        ax4.set_ylim([-1.9, 1.9])

        ax3.patch.set_visible(False)
        ax3.set_zorder(ax4.get_zorder() + 1)

        #*******************
        # prettify
        minorLocator = MultipleLocator(1)
        ax1.set_ylim([-60, 100])
        ax1.yaxis.set_ticks([-50, 0, 50, 100])
        for ax in [ax2, ax3]:
            ax.set_ylim([-50, 50])
            ax.axhline(0, c='0.5', ls='--')
            ax.legend(loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
                              labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=BBOX)
            ax.xaxis.set_minor_locator(minorLocator)
            ax.yaxis.set_ticks_position('left')
            utils.thicken_panel_border(ax)

        ax2.set_ylabel("Anomaly (mm yr" + r'$^{-1}$' + ")",
                       fontsize=settings.FONTSIZE)
        plt.setp(ax1.get_xticklabels(), visible=False)
        plt.setp(ax2.get_xticklabels(), visible=False)

        ax4.set_xlim([1979, int(settings.YEAR) + 1])
        ax4.yaxis.set_label_position("right")
        ax3.yaxis.set_tick_params(right=False)
        utils.thicken_panel_border(ax4)

        for ax in [ax1, ax2, ax3]:
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
        for tick in ax3.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for tick in ax4.yaxis.get_major_ticks():
            tick.label2.set_fontsize(settings.FONTSIZE)

        # sort labelling
        ax1.text(0.02,
                 0.9,
                 "(a) Land in Situ",
                 transform=ax1.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax2.text(0.02,
                 0.9,
                 "(b) Ocean",
                 transform=ax2.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax3.text(0.02,
                 0.9,
                 "(c) Globe",
                 transform=ax3.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)

        plt.savefig(settings.IMAGELOC +
                    "PCP_ts_3panel{}".format(settings.OUTFMT))
        plt.close()

    # 3-panel plot for 2019 report
    if True:
        fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(8, 8), sharex=True)

        # Land
        ghcn, gpcc, gpcp = read_land(DATALOC +
                                     "Land_insitu_timeseries-1979.dat")
        utils.plot_ts_panel(ax1, [ghcn, gpcc, gpcp],
                            "-",
                            "hydrological",
                            loc=LEGEND_LOC,
                            bbox=BBOX)

        # Ocean
        gpcp = read_ocean(DATALOC + "Ocean_insitu_timeseries-1979.dat")
        utils.plot_ts_panel(ax2, [gpcp],
                            "-",
                            "hydrological",
                            loc="",
                            bbox=BBOX)

        # Globe
        gpcp = read_ocean(DATALOC + "Global_insitu_timeseries-1979.dat")
        utils.plot_ts_panel(ax3, [gpcp],
                            "-",
                            "hydrological",
                            loc="",
                            bbox=BBOX)

        #*******************
        # prettify
        fig.subplots_adjust(right=0.98, bottom=0.08, top=0.98, hspace=0.001)

        minorLocator = MultipleLocator(1)
        ax1.set_ylim([-60, 100])
        ax1.yaxis.set_ticks([-50, 0, 50, 100])
        ax2.set_ylim([-29, 43])
        ax3.set_ylim([-29, 43])
        for ax in [ax1, ax2, ax3]:
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

        for tick in ax3.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        ax2.set_ylabel("Anomaly (mm yr" + r'$^{-1}$' + ")",
                       fontsize=settings.FONTSIZE)

        # sort labelling
        ax1.text(0.02,
                 0.9,
                 "(a) Land in Situ",
                 transform=ax1.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax2.text(0.02,
                 0.9,
                 "(b) Ocean",
                 transform=ax2.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax3.text(0.02,
                 0.9,
                 "(c) Globe",
                 transform=ax3.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)

        plt.savefig(settings.IMAGELOC +
                    "PCP_ts_3panel{}".format(settings.OUTFMT))
        plt.close()

    #************************************************************************
    # GPCP map
    if True:
        cube = read_map(
            DATALOC +
            "GPCP_{}anomaly_base_1981-2000.txt".format(settings.YEAR))
        bounds = [-2000, -400, -300, -200, -100, 0, 100, 200, 300, 400, 2000]

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "PCP_{}_anoms_gpcp".format(settings.YEAR),
            cube, settings.COLOURMAP_DICT["hydrological"], bounds,
            "Anomalies from 1981-2000 (mm)")
        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "p2.1_PCP_{}_anoms_gpcp".format(settings.YEAR),
            cube,
            settings.COLOURMAP_DICT["hydrological"],
            bounds,
            "Anomalies from 1981-2000 (mm)",
            figtext="(k) Precipitation")

    #************************************************************************
    # GPCP map - Ocean only

    # # Read Oceans
    # print "FIX YEAR"
    # cube = iris.load(DATALOC + "ocean_precipitation_sotc2015.nc", "anomaly_map")[0]

    # # add in the coordinates which haven't been stored sensibly
    # for c, coord in enumerate(["latitude", "longitude"]):
    #     coord_cube = iris.load(DATALOC + "ocean_precipitation_sotc2015.nc", coord)[0]
    #     if c == 0:
    #         iris_coord = iris.coords.DimCoord(coord_cube.data[:,0], standard_name=coord, units='degrees')
    #     elif c == 1:
    #         iris_coord = iris.coords.DimCoord(coord_cube.data[0], standard_name=coord, units='degrees')

    #     cube.add_dim_coord(iris_coord,c)
    #     cube.coord(coord).guess_bounds()

    # bounds=[-2000, -400, -300, -200, -100, 0, 100, 200, 300, 400, 2000]

    # utils.plot_smooth_map_iris(settings.IMAGELOC + "PCP_{}_anoms_gpcp_ocean".format(settings.YEAR), cube, settings.COLOURMAP_DICT["hydrological"], bounds, "Anomalies from 1981-2000 (mm)")

    return  # run_all_plots
Пример #6
0
def run_all_plots():

    if True:
        # multipanel timeseries

        COLOURS = settings.COLOURS["temperature"]
        fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6,
                                                           figsize=(8, 19),
                                                           sharex=True)

        # ERA5
        era5_globe, era5_ocean, era5_land, era5tropics = utils.era5_ts_read(
            settings.REANALYSISLOC, "sat", annual=True)
        land_era5_clim, land_era5_anoms = utils.calculate_climatology_and_anomalies_1d(
            era5_land, 1981, 2010)
        ocean_era5_clim, ocean_era5_anoms = utils.calculate_climatology_and_anomalies_1d(
            era5_ocean, 1981, 2010)
        global_era5_clim, global_era5_anoms = utils.calculate_climatology_and_anomalies_1d(
            era5_globe, 1981, 2010)

        #*******************
        # in situ L+O
        noaa, nasa, jma = read_global_t(DATALOC +
                                        "{}_LO.csv".format(IS_timeseries_root))

        hadcrut = read_hadcrut_crutem(DATALOC + "hadcrut4.1981-2010.csv")

        p0 = ax1.plot(noaa.times,
                      noaa.data,
                      c=COLOURS[noaa.name],
                      ls='-',
                      label=noaa.name,
                      lw=LW)
        p1 = ax1.plot(nasa.times,
                      nasa.data,
                      c=COLOURS[nasa.name],
                      ls='-',
                      label=nasa.name,
                      lw=LW)
        #     p2 = ax1.plot(jma.times, jma.data, c=COLOURS[jma.name], ls='-', label=jma.name, lw=LW)
        p3 = ax1.plot(hadcrut.times,
                      hadcrut.data,
                      c=COLOURS[hadcrut.name],
                      ls='-',
                      label=hadcrut.name,
                      lw=LW)
        ax1.fill_between(hadcrut.times, hadcrut.lower, hadcrut.upper, \
                             where=hadcrut.upper > hadcrut.lower, color='0.5', alpha=0.7)
        p4 = ax1.fill(np.NaN, np.NaN, '0.5', alpha=0.7)

        ax1.axhline(0, c='0.5', ls='--')

        ax1.legend([p0[0], p1[0], (p3[0], p4[0])], [noaa.name, nasa.name, hadcrut.name], \
                       loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
                       labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=BBOX)

        ax1.text(0.02,
                 0.9,
                 "(a) In Situ Land and Ocean",
                 transform=ax1.transAxes,
                 fontsize=settings.FONTSIZE)

        utils.thicken_panel_border(ax1)
        # ax1.yaxis.set_ticks_position('left')

        #*******************
        # reanalysis L+O

        merra = utils.read_merra(
            settings.REANALYSISLOC +
            "MERRA-2_SfcAnom{}.dat".format(settings.YEAR), "temperature", "LO")
        jra_actuals, jra_anoms = utils.read_jra55(
            settings.REANALYSISLOC + "JRA-55_tmp2m_global_ts.txt",
            "temperature")
        twenty_cr_actuals = utils.read_20cr(
            settings.REANALYSISLOC + "global.2mt.skt.txt", "temperature")
        dummy, twenty_cr_anoms = utils.calculate_climatology_and_anomalies_1d(
            twenty_cr_actuals, 1981, 2010)
        twenty_cr_anoms.zorder = -1

        # 2018 no MERRA
        utils.plot_ts_panel(ax2, [jra_anoms, global_era5_anoms],
                            "-",
                            "temperature",
                            loc=LEGEND_LOC,
                            bbox=BBOX)

        ax2.text(0.02,
                 0.9,
                 "(b) Reanalysis Land and Ocean",
                 transform=ax2.transAxes,
                 fontsize=settings.FONTSIZE)

        #*******************
        # in situ L

        noaa, nasa, jma = read_global_t(DATALOC +
                                        "{}_L.csv".format(IS_timeseries_root))
        crutem = read_hadcrut_crutem(DATALOC +
                                     "crutem4_new_logo.1981-2010.csv")

        p0 = ax3.plot(noaa.times,
                      noaa.data,
                      ls='-',
                      c=COLOURS[noaa.name],
                      label=noaa.name,
                      lw=LW)
        p1 = ax3.plot(nasa.times,
                      nasa.data,
                      ls='-',
                      c=COLOURS[nasa.name],
                      label=nasa.name,
                      lw=LW)
        #    p2 = ax3.plot(jma.times, jma.data, ls='-', c=COLOURS[jma.name], label=jma.name, lw=LW)
        #    p3 = ax3.plot(berkeley.times, berkeley.data, ls = '-', c = COLOURS[berkeley.name], label = berkeley.name, lw = LW)
        p4 = ax3.plot(crutem.times,
                      crutem.data,
                      ls='-',
                      c=COLOURS[crutem.name],
                      label=crutem.name,
                      lw=LW)
        ax3.fill_between(crutem.times, crutem.lower, crutem.upper, \
                             where=crutem.upper > crutem.lower, color='0.5', alpha=0.7)
        p5 = ax1.fill(np.NaN, np.NaN, '0.5', alpha=0.7)

        ax3.axhline(0, c='0.5', ls='--')

        ax3.legend([p0[0], p1[0], (p4[0], p5[0])], [noaa.name, nasa.name, crutem.name], \
                       loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
                       labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=BBOX)

        ax3.text(0.02,
                 0.9,
                 "(c) In Situ Land only",
                 transform=ax3.transAxes,
                 fontsize=settings.FONTSIZE)

        utils.thicken_panel_border(ax3)
        #    ax3.yaxis.set_ticks_position('left')

        #*******************
        # reanalysis L

        merra = utils.read_merra(
            settings.REANALYSISLOC +
            "MERRA-2_SfcAnom{}.dat".format(settings.YEAR), "temperature", "L")
        jra_actual, jra_anoms = utils.read_jra55(
            settings.REANALYSISLOC + "JRA-55_tmp2m_globalland_ts.txt",
            "temperature")
        twenty_cr_actuals = utils.read_20cr(
            settings.REANALYSISLOC + "air2mland.txt", "temperature")
        dummy, twenty_cr_anoms = utils.calculate_climatology_and_anomalies_1d(
            twenty_cr_actuals, 1981, 2010)
        twenty_cr_anoms.zorder = -1

        # 2018 - No MERRA
        utils.plot_ts_panel(ax4, [jra_anoms, land_era5_anoms],
                            "-",
                            "temperature",
                            loc=LEGEND_LOC,
                            bbox=BBOX)

        ax4.text(0.02,
                 0.9,
                 "(d) Reanalysis Land only",
                 transform=ax4.transAxes,
                 fontsize=settings.FONTSIZE)

        #*******************
        # in situ O

        noaa, nasa, jma = read_global_t(DATALOC +
                                        "{}_O.csv".format(IS_timeseries_root))
        hadsst = read_hadcrut_crutem(DATALOC +
                                     "hadsst3_new_logo.1981-2010.csv")

        p0 = ax5.plot(noaa.times,
                      noaa.data,
                      ls='-',
                      c=COLOURS[noaa.name],
                      label=noaa.name,
                      lw=LW)
        p1 = ax5.plot(nasa.times,
                      nasa.data,
                      ls='-',
                      c=COLOURS[nasa.name],
                      label=nasa.name,
                      lw=LW)
        #     p2 = ax5.plot(jma.times, jma.data, ls='-', c=COLOURS[jma.name], label=jma.name, lw=LW)
        p3 = ax5.plot(hadsst.times,
                      hadsst.data,
                      ls='-',
                      c=COLOURS[hadsst.name],
                      label=hadsst.name,
                      lw=LW)
        ax5.fill_between(hadsst.times, hadsst.lower, hadsst.upper, \
                             where=hadsst.upper > hadsst.lower, color='0.5', alpha=0.7)
        p4 = ax1.fill(np.NaN, np.NaN, '0.5', alpha=0.7)

        ax5.axhline(0, c='0.5', ls='--')

        ax5.legend([p0[0], p1[0], (p3[0], p4[0])], [noaa.name, nasa.name, hadsst.name], \
                       loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
                       labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=BBOX)

        ax5.text(0.02,
                 0.9,
                 "(e) In Situ Ocean only",
                 transform=ax5.transAxes,
                 fontsize=settings.FONTSIZE)

        utils.thicken_panel_border(ax5)
        #    ax5.yaxis.set_ticks_position('left')

        #*******************
        # reanalysis O

        merra = utils.read_merra(
            settings.REANALYSISLOC +
            "MERRA-2_SfcAnom{}.dat".format(settings.YEAR), "temperature", "O")
        jra_actual, jra_anoms = utils.read_jra55(
            settings.REANALYSISLOC + "JRA-55_tmp2m_globalocean_ts.txt",
            "temperature")
        twenty_cr_actuals = utils.read_20cr(
            settings.REANALYSISLOC + "airsktocean.txt", "temperature")
        dummy, twenty_cr_anoms = utils.calculate_climatology_and_anomalies_1d(
            twenty_cr_actuals, 1981, 2010)
        twenty_cr_anoms.zorder = -1

        # 2018 no MERRA
        utils.plot_ts_panel(ax6, [jra_anoms, ocean_era5_anoms],
                            "-",
                            "temperature",
                            loc=LEGEND_LOC,
                            bbox=BBOX)

        ax6.text(0.02,
                 0.9,
                 "(f) Reanalysis Ocean only",
                 transform=ax6.transAxes,
                 fontsize=settings.FONTSIZE)

        #*******************
        # prettify

        fig.text(0.03,
                 0.5,
                 "Anomalies (" + r'$^{\circ}$' + "C)",
                 va='center',
                 rotation='vertical',
                 fontsize=settings.FONTSIZE)

        plt.xlim([1900, int(settings.YEAR) + 2])

        minorLocator = MultipleLocator(5)
        for ax in [ax1, ax2, ax3, ax4, ax5, ax6]:
            ax.set_ylim(YLIM)
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
            ax.xaxis.set_minor_locator(minorLocator)

        for tick in ax6.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        fig.subplots_adjust(right=0.96, top=0.995, bottom=0.02, hspace=0.001)

        plt.savefig(settings.IMAGELOC + "SAT_ts{}".format(settings.OUTFMT))

        plt.close()

    #************************************************************************
    # ERA5 Anomaly figure

    if True:
        # Read in ERA anomalies

        cube_list = iris.load(settings.REANALYSISLOC +
                              "era5_t2m_{}01-{}12_ann_ano.nc".format(
                                  settings.YEAR, settings.YEAR))
        for cube in cube_list:
            if cube.var_name == "T2M":
                break

        cube.coord('latitude').guess_bounds()
        cube.coord('longitude').guess_bounds()

        bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "SAT_{}_anoms_era5".format(settings.YEAR),
            cube[0],
            settings.COLOURMAP_DICT["temperature"],
            bounds,
            "Anomalies from 1981-2010 (" + r'$^{\circ}$' + "C)",
            title="ERA5")

    #************************************************************************
    # MERRA2 Anomaly figure
    if True:
        cube_list = iris.load(settings.REANALYSISLOC +
                              "MERRA-2_SfcAnom_{}.nc".format(settings.YEAR))
        for cube in cube_list:
            if cube.var_name == "t2ma":
                break

        cube.coord('latitude').guess_bounds()
        cube.coord('longitude').guess_bounds()

        bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "SAT_{}_anoms_merra".format(settings.YEAR), cube[0], \
                                       settings.COLOURMAP_DICT["temperature"], bounds, \
                                       "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="MERRA-2")

    #************************************************************************
    # HadCRUT4 Anomaly figure
    if True:
        cube_list = iris.load(DATALOC + "HadCRUT.4.6.0.0.median.nc")
        for cube in cube_list:
            if cube.var_name == "temperature_anomaly":
                break

        cube.coord('latitude').guess_bounds()
        cube.coord('longitude').guess_bounds()

        # restrict to 1851 to last full year
        date_constraint = utils.periodConstraint(
            cube, dt.datetime(1850, 1, 1),
            dt.datetime(int(settings.YEAR) + 1, 1, 1))
        cube = cube.extract(date_constraint)

        # convert to 1981-2010 climatology.
        clim_constraint = utils.periodConstraint(cube, dt.datetime(1981, 1, 1),
                                                 dt.datetime(2011, 1, 1))
        clim_cube = cube.extract(clim_constraint)

        clim_data = clim_cube.data.reshape(-1, 12, clim_cube.data.shape[-2],
                                           clim_cube.data.shape[-1])

        # more than 15 years present
        climatology = np.ma.mean(clim_data, axis=0)
        nyears = np.ma.count(clim_data, axis=0)
        climatology = np.ma.masked_where(nyears <= 15,
                                         climatology)  # Kate keeps GT 15.

        # extract final year
        final_year_constraint = utils.periodConstraint(
            cube, dt.datetime(int(settings.YEAR), 1, 1),
            dt.datetime(int(settings.YEAR) + 1, 1, 1))
        final_year_cube = cube.extract(final_year_constraint)

        final_year_cube.data = final_year_cube.data - climatology

        # more than 6 months present
        annual_cube = final_year_cube.collapsed(['time'], iris.analysis.MEAN)
        nmonths = np.ma.count(final_year_cube.data, axis=0)
        annual_cube.data = np.ma.masked_where(nmonths <= 6, annual_cube.data)

        bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "SAT_{}_anoms_hadcrut4".format(settings.YEAR), annual_cube, \
                                       settings.COLOURMAP_DICT["temperature"], bounds, \
                                       "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="HadCRUT 4.6")

    #************************************************************************
    # NOAA data Anomaly figure - incl plate 2.1
    if True:
        cube = read_noaa_mlost(DATALOC + "mlost-box.ytd.12.1981-2010bp.txt",
                               int(settings.YEAR))

        bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_SAT_{}_anoms_noaa".format(settings.YEAR), cube, \
                                       settings.COLOURMAP_DICT["temperature"], bounds, \
                                       "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", \
                                       figtext="(a) Surface Temperature", \
                                       save_netcdf_filename="{}MLOST_for_NOAA_{}.nc".format(DATALOC, dt.datetime.strftime(dt.datetime.now(), "%d-%b-%Y")))

        utils.plot_smooth_map_iris(settings.IMAGELOC + "SAT_{}_anoms_noaa".format(settings.YEAR), cube, \
                                       settings.COLOURMAP_DICT["temperature"], bounds, \
                                       "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="NOAAGlobalTemp")

    #************************************************************************
    # JRA55 data Anomaly figure
    if True:
        cube_list = iris.load(settings.REANALYSISLOC +
                              "jra55_t2m_{}01-{}12_ann_ano.nc".format(
                                  settings.YEAR, settings.YEAR))
        for cube in cube_list:
            if cube.var_name == "T2M":
                break

        cube.coord('latitude').guess_bounds()
        cube.coord('longitude').guess_bounds()

        bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "SAT_{}_anoms_jra55".format(settings.YEAR), cube[0,0], \
                                       settings.COLOURMAP_DICT["temperature"], bounds, \
                                       "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="JRA-55")

    #************************************************************************
    # NASA GISS Anomaly figure
    if True:
        #cube = read_nasa_giss(DATALOC + "nasa-2015-anomalies-wrt1981-2010bp")

        cube = iris.load(DATALOC + "gistemp1200_GHCNv4_ERSSTv5.nc")[0]

        # convert to 1981-2010 climatology.
        clim_constraint = utils.periodConstraint(cube, dt.datetime(1981, 1, 1),
                                                 dt.datetime(2011, 1, 1))
        clim_cube = cube.extract(clim_constraint)

        clim_data = clim_cube.data.reshape(-1, 12, clim_cube.data.shape[-2],
                                           clim_cube.data.shape[-1])

        # more than 15 years present
        climatology = np.ma.mean(clim_data, axis=0)
        nyears = np.ma.count(clim_data, axis=0)
        climatology = np.ma.masked_where(nyears <= 15,
                                         climatology)  # Kate keeps GT 15.

        # extract final year
        final_year_constraint = utils.periodConstraint(cube, dt.datetime(int(settings.YEAR), 1, 1), \
                                                           dt.datetime(int(settings.YEAR)+1, 1, 1))
        final_year_cube = cube.extract(final_year_constraint)

        final_year_cube.data = final_year_cube.data - climatology

        # more than 6 months present
        annual_cube = final_year_cube.collapsed(['time'], iris.analysis.MEAN)
        nmonths = np.ma.count(final_year_cube.data, axis=0)
        annual_cube.data = np.ma.masked_where(nmonths <= 6, annual_cube.data)

        bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "SAT_{}_anoms_nasa".format(settings.YEAR), annual_cube, \
                                       settings.COLOURMAP_DICT["temperature"], bounds, \
                                       "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="NASA GISS")

    return  # run_all_plots
Пример #7
0
def run_all_plots():

    #************************************************************************
    # Timeseries plot
    if True:

        monthly = read_data(DATALOC + "monthlist", "AOD monthly")
        annual = read_data(DATALOC + "yearlist", "AOD annual")

        minor_tick_interval = 1
        minorLocator = MultipleLocator(minor_tick_interval)
        COLOURS = settings.COLOURS["composition"]

        fig = plt.figure(figsize=(8, 5))
        ax = plt.axes([0.13, 0.07, 0.85, 0.86])

        plt.plot(monthly.times,
                 monthly.data,
                 COLOURS[monthly.name],
                 ls='-',
                 label=monthly.name,
                 lw=LW)
        plt.plot(annual.times,
                 annual.data,
                 COLOURS[annual.name],
                 ls='-',
                 label=annual.name,
                 lw=LW)

        ax.legend(loc=LEGEND_LOC,
                  ncol=1,
                  frameon=False,
                  prop={'size': settings.LEGEND_FONTSIZE},
                  labelspacing=0.1,
                  columnspacing=0.5)

        # prettify
        ax.xaxis.set_minor_locator(minorLocator)
        utils.thicken_panel_border(ax)

        fig.text(0.03,
                 0.5,
                 "AOD",
                 va='center',
                 rotation='vertical',
                 fontsize=settings.FONTSIZE)

        plt.xlim([2002.5, int(settings.YEAR) + 1.5])
        plt.ylim([0.09, 0.21])
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        plt.savefig(settings.IMAGELOC + "ASL_ts{}".format(settings.OUTFMT))
        plt.close()

    #************************************************************************
    # Global maps

    # total
    if True:
        total = iris.load(DATALOC + "diffAOD.nc")  #.format(settings.YEAR))
        bounds = np.array([
            -10, -0.15, -0.10, -0.05, -0.025, -0.01, 0.01, 0.025, 0.05, 0.10,
            0.15, 10
        ])

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "ASL_total_anomalies_{}".format(settings.YEAR),
            total[0][0], settings.COLOURMAP_DICT["composition"], bounds,
            "Anomalies from 2003-{} (AOD)".format(settings.YEAR[2:]))
        utils.plot_smooth_map_iris(
            settings.IMAGELOC +
            "p2.1_ASL_total_anomalies_{}".format(settings.YEAR),
            total[0][0],
            settings.COLOURMAP_DICT["composition"],
            bounds,
            "Anomalies from 2003-20{} (AOD)".format(
                int(settings.YEAR[2:]) - 1),
            figtext="(x) Total Aerosol")

    # extreme AOD
    if True:
        extreme = iris.load(DATALOC + "NB999.nc")  #.format(settings.YEAR))
        bounds = np.array([0, 2.5, 5, 10, 20, 30, 40, 90])

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "ASL_extreme_days_{}".format(settings.YEAR),
            extreme[0][0], plt.cm.YlOrBr, bounds,
            "Number of days with AOD above the 99.9th percentile (days)")
        utils.plot_smooth_map_iris(
            settings.IMAGELOC +
            "p2.1_ASL_extreme_days_{}".format(settings.YEAR),
            extreme[0][0],
            plt.cm.YlOrBr,
            bounds,
            "Number of days with AOD above the 99.9th percentile (days)",
            figtext="(y) Extreme Aerosol Days")

    # Biomass Burning
    if False:
        BB = iris.load(DATALOC + "diffBB.nc")  #.format(settings.YEAR))

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "ASL_BB_anomalies_{}".format(settings.YEAR),
            BB[0], settings.COLOURMAP_DICT["composition"], bounds,
            "Anomalies from 2003-20{} (AOD)".format(
                int(settings.YEAR[2:]) - 1))
        utils.plot_smooth_map_iris(
            settings.IMAGELOC +
            "p2.1_ASL_BB_anomalies_{}".format(settings.YEAR),
            BB[0],
            settings.COLOURMAP_DICT["composition"],
            bounds,
            "Anomalies from 2003-20{} (AOD)".format(
                int(settings.YEAR[2:]) - 1),
            figtext="(y) Black Carbon & Organic Matter Aerosol")

    # Dust
    if False:
        dust = iris.load(DATALOC + "diffDU.nc")  #.format(settings.YEAR))

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "ASL_dust_anomalies_{}".format(settings.YEAR),
            dust[0], settings.COLOURMAP_DICT["composition"], bounds,
            "Anomalies from 2003-20{} (AOD)".format(
                int(settings.YEAR[2:]) - 1))
        utils.plot_smooth_map_iris(
            settings.IMAGELOC +
            "p2.1_ASL_dust_anomalies_{}".format(settings.YEAR),
            dust[0],
            settings.COLOURMAP_DICT["composition"],
            bounds,
            "Anomalies from 2003-20{} (AOD)".format(
                int(settings.YEAR[2:]) - 1),
            figtext="(z) Dust Aerosol")

    #************************************************************************
    # Total, Trend and Event map
    if False:

        # as one colorbar per map, don't use the utils Iris routine

        fig = plt.figure(figsize=(8, 15))

        #total = iris.load(DATALOC + "Aerosol_Fig2a_Total_Averages.nc")
        #trend = iris.load(DATALOC + "Aerosol_Fig2b_Total_Trends.nc")
        #event = iris.load(DATALOC + "Aerosol_Fig2c_ExtremeDayCounts_{}.nc".format(settings.YEAR))

        total = iris.load(DATALOC + "meanAOD.nc")
        trend = iris.load(DATALOC + "trend.nc")
        number = iris.load(DATALOC + "numbermonth.nc")

        bounds_a = np.array(
            [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.7, 1.0])
        bounds_b = np.array([
            -10, -0.010, -0.005, -0.003, -0.002, -0.001, 0.001, 0.002, 0.003,
            0.005, 0.010, 10
        ])
        bounds_c = np.array([0, 1, 2, 3, 4, 5, 6, 7, 10])

        all_cubes = [total, trend, number]
        all_bounds = [bounds_a, bounds_b, bounds_c]

        # do colourmaps by hand
        cmap = [
            plt.cm.YlOrBr, settings.COLOURMAP_DICT["composition"],
            plt.cm.YlOrBr
        ]
        PLOTLABELS = ["(a)", "(b)", "(c)"]
        cb_label = ["AOD", "AOD yr" + r'$^{-1}$', "Months"]

        # spin through axes
        for a in range(3):

            norm = mpl.cm.colors.BoundaryNorm(all_bounds[a], cmap[a].N)

            ax = plt.subplot(3, 1, a + 1, projection=cartopy.crs.Robinson())

            ax.gridlines()  #draw_labels=True)
            ax.add_feature(cartopy.feature.LAND,
                           zorder=0,
                           facecolor="0.9",
                           edgecolor="k")
            ax.coastlines()

            ext = ax.get_extent()  # save the original extent

            mesh = iris.plot.pcolormesh(all_cubes[a][0],
                                        cmap=cmap[a],
                                        norm=norm,
                                        axes=ax)

            ax.set_extent(
                ext, ax.projection)  # fix the extent change from colormesh
            ax.text(0.0,
                    1.0,
                    PLOTLABELS[a],
                    fontsize=settings.FONTSIZE * 0.8,
                    transform=ax.transAxes)

            # sort the colourbar
            cb = fig.colorbar(mesh, ax=ax, orientation='horizontal', \
                                  ticks=all_bounds[a][1:-1], label=cb_label[a], drawedges=True, pad=0.05, fraction=0.07, aspect=30)
            if a == 1:
                cb.set_ticklabels(
                    ["{:6.3f}".format(b) for b in all_bounds[a][1:-1]])
            else:
                cb.set_ticklabels(
                    ["{:g}".format(b) for b in all_bounds[a][1:-1]])

            cb.outline.set_linewidth(2)
            cb.dividers.set_color('k')
            cb.dividers.set_linewidth(2)

        fig.subplots_adjust(bottom=0.05,
                            top=0.95,
                            left=0.04,
                            right=0.95,
                            wspace=0.02)

        plt.savefig(settings.IMAGELOC + "ASL_Trends{}".format(settings.OUTFMT))

        plt.close()

    #************************************************************************
    # Total, and two trends maps
    if True:

        # as one colorbar per map, don't use the utils Iris routine

        fig = plt.figure(figsize=(8, 15))

        total = iris.load(DATALOC + "AOD2003-2009.nc")[0]
        trend1 = iris.load(DATALOC + "trend2003-2019.nc")[0]
        trend1.data = np.ma.masked_where(trend1.data == -99, trend1.data)
        trend2 = iris.load(DATALOC + "medianaod12-19sig.nc")[0]
        trend2.data = np.ma.masked_where(trend2.data == -99, trend2.data)

        bounds_a = np.array(
            [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.7, 1.0])
        bounds_b = np.array([
            -10, -0.020, -0.010, -0.006, -0.004, -0.002, 0.002, 0.004, 0.006,
            0.010, 0.020, 10
        ])
        bounds_c = np.array([
            -10, -0.020, -0.010, -0.006, -0.004, -0.002, 0.002, 0.004, 0.006,
            0.010, 0.020, 10
        ])

        all_cubes = [total, trend1, trend2]
        all_bounds = [bounds_a, bounds_b, bounds_c]

        # do colourmaps by hand
        cmap = [
            plt.cm.YlOrBr, settings.COLOURMAP_DICT["composition"],
            settings.COLOURMAP_DICT["composition"]
        ]
        PLOTLABELS = [
            "(a) Mean 2003-19", "(b) Trend 2003-19", "(c) Trend 2012-19"
        ]
        cb_label = ["AOD", "AOD yr" + r'$^{-1}$', "AOD yr" + r'$^{-1}$']

        # spin through axes
        for a in range(3):

            norm = mpl.cm.colors.BoundaryNorm(all_bounds[a], cmap[a].N)

            ax = plt.subplot(3, 1, a + 1, projection=cartopy.crs.Robinson())

            ax.gridlines()  #draw_labels=True)
            ax.add_feature(cartopy.feature.LAND,
                           zorder=0,
                           facecolor="0.9",
                           edgecolor="k")
            ax.coastlines()

            ext = ax.get_extent()  # save the original extent

            cube = all_cubes[a][0]
            if settings.OUTFMT in [".eps", ".pdf"]:
                if cube.coord("latitude").points.shape[0] > 180 or cube.coord(
                        "longitude").points.shape[0] > 360:
                    regrid_size = 1.0
                    print(
                        "Regridding cube for {} output to {} degree resolution"
                        .format(settings.OUTFMT, regrid_size))
                    print("Old Shape {}".format(cube.data.shape))
                    plot_cube = utils.regrid_cube(cube, regrid_size,
                                                  regrid_size)
                    print("New Shape {}".format(plot_cube.data.shape))
                else:
                    plot_cube = copy.deepcopy(cube)
            else:
                plot_cube = copy.deepcopy(cube)

            mesh = iris.plot.pcolormesh(plot_cube,
                                        cmap=cmap[a],
                                        norm=norm,
                                        axes=ax)

            ax.set_extent(
                ext, ax.projection)  # fix the extent change from colormesh
            ax.text(0.0,
                    1.0,
                    PLOTLABELS[a],
                    fontsize=settings.FONTSIZE * 0.8,
                    transform=ax.transAxes)

            # sort the colourbar
            cb = fig.colorbar(mesh, ax=ax, orientation='horizontal', \
                                  ticks=all_bounds[a][1:-1], label=cb_label[a], drawedges=True, pad=0.05, fraction=0.07, aspect=30)
            if a == 1:
                cb.set_ticklabels(
                    ["{:6.3f}".format(b) for b in all_bounds[a][1:-1]])
            else:
                cb.set_ticklabels(
                    ["{:g}".format(b) for b in all_bounds[a][1:-1]])

            cb.outline.set_linewidth(2)
            cb.dividers.set_color('k')
            cb.dividers.set_linewidth(2)

        fig.subplots_adjust(bottom=0.05,
                            top=0.95,
                            left=0.04,
                            right=0.95,
                            wspace=0.02)

        plt.savefig(settings.IMAGELOC + "ASL_Trends{}".format(settings.OUTFMT))

        plt.close()

    #************************************************************************
    # Forcing map
    if True:

        bounds = np.array([
            -10, -1.4, -1.0, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 1.0, 1.4, 10
        ])

        RFari = iris.load(
            DATALOC + "aerorf_camsra_rfari_2003-{}.nc".format(settings.YEAR))

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "ASL_RFari_anomalies_{}".format(settings.YEAR),
            RFari[0][0],
            settings.COLOURMAP_DICT["composition"],
            bounds,
            "Anomalies from 2003-{}".format(settings.YEAR),
            figtext="(a) CAMSRA: RFari (SW). Mean -0.56" + r'$\pm$' +
            "0.16 Wm" + r'$^{-1}$')

        RFaci = iris.load(
            DATALOC + "aerorf_camsra_rfaci_2003-{}.nc".format(settings.YEAR))

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "ASL_RFaci_anomalies_{}".format(settings.YEAR),
            RFaci[0][0],
            settings.COLOURMAP_DICT["composition"],
            bounds,
            "Anomalies from 2003-{}".format(settings.YEAR),
            figtext="(c) CAMSRA: RFaci (SW). Mean -0.80" + r'$\pm$' +
            "0.53 Wm" + r'$^{-1}$')

        # and timeseries
        cubelist = iris.load(
            DATALOC +
            "aerorf_camsra_timeseries_2003-{}.nc".format(settings.YEAR))

        LABELS = {"RFari": "(b)", "RFaci": "(d)"}
        ERRORS = {"RFari": 0.286, "RFaci": 0.667}

        for cube in cubelist:

            name = str(cube.var_name)
            name = name[:2].upper() + name[2:]

            fig = plt.figure(figsize=(8, 6))
            ax = plt.axes([0.13, 0.10, 0.8, 0.86])
            iris.plot.plot(cube, 'k', label=cube.var_name, lw=LW)

            timeUnits = cube.coord("time").units
            dt_time = timeUnits.num2date(cube.coord("time").points)
            upper = cube.data * (1 + ERRORS[name])
            lower = cube.data * (1 - ERRORS[name])
            ax.fill_between(dt_time, upper, lower, color="0.7", label=None)

            # prettify
            ax.set_ylabel("{} (W m".format(name) + r'$^{-2}$' + ")",
                          fontsize=settings.FONTSIZE)

            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
            for tick in ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
            ax.yaxis.set_ticks_position('left')
            utils.thicken_panel_border(ax)

            minorLocator = MultipleLocator(365.242199)  # in days since
            ax.xaxis.set_minor_locator(minorLocator)
            utils.thicken_panel_border(ax)

            # set labels
            if cube.var_name == "rfari":
                ax.text(0.02, 0.9, "(b)")
                ax.set_ylim([-0.8, -0.3])
            else:
                ax.text(0.02, 0.9, "(d")
                ax.set_ylim([-1.6, -0.2])

            ax.text(0.02,
                    0.9,
                    LABELS[name],
                    transform=ax.transAxes,
                    fontsize=settings.FONTSIZE)

            plt.savefig(settings.IMAGELOC +
                        "ASL_ts_{}{}".format(cube.var_name, settings.OUTFMT))
            plt.close()

    return  # run_all_plots
Пример #8
0
def run_all_plots():

    if True:
        #***************
        # Figure 1

        euro, africa, tibet, canada = read_ts(DATALOC +
                                              "BAMS2020Fig1_data_LSWT.csv")
        #        euro_fit, africa_fit, tibet_fit, canada_fit = read_ts(DATALOC + "Fig1_lines_LSWT.csv")

        euro_fit = utils.Timeseries("Lake", [1994, 2020],
                                    [-0.5136, (2020 - 1994) * 0.0386 - 0.5136])
        africa_fit = utils.Timeseries(
            "Lake", [1994, 2020], [0.0204, (2020 - 1994) * 0.0036 + 0.0204])
        tibet_fit = utils.Timeseries("Lake", [1994, 2020],
                                     [0.0878, (2020 - 1994) * 0.0017 + 0.0878])
        canada_fit = utils.Timeseries(
            "Lake", [1994, 2020], [-0.2018, (2020 - 1994) * 0.0223 - 0.2018])

        fig, (ax1, ax2, ax3, ax4) = plt.subplots(4,
                                                 figsize=(8, 10),
                                                 sharex=True)

        #***************
        # the timeseries
        LEGEND_LOC = ""

        utils.plot_ts_panel(ax1, [euro], "-", "temperature", loc=LEGEND_LOC)
        ax1.plot(euro_fit.times,
                 euro_fit.data,
                 c=settings.COLOURS["temperature"][euro_fit.name],
                 lw=2,
                 ls="--")
        ax1.text(1995, 0.8, "Europe, 127 lakes", fontsize=settings.FONTSIZE)
        utils.plot_ts_panel(ax2, [africa], "-", "temperature", loc=LEGEND_LOC)
        ax2.plot(africa_fit.times,
                 africa_fit.data,
                 c=settings.COLOURS["temperature"][africa_fit.name],
                 lw=2,
                 ls="--")
        ax2.text(1995, 0.8, "Africa, 68 lakes", fontsize=settings.FONTSIZE)
        utils.plot_ts_panel(ax3, [tibet], "-", "temperature", loc=LEGEND_LOC)
        ax3.plot(tibet_fit.times,
                 tibet_fit.data,
                 c=settings.COLOURS["temperature"][tibet_fit.name],
                 lw=2,
                 ls="--")
        ax3.text(1995,
                 0.8,
                 "Tibetan Plateau, 106 lakes",
                 fontsize=settings.FONTSIZE)
        utils.plot_ts_panel(ax4, [canada], "-", "temperature", loc=LEGEND_LOC)
        ax4.plot(canada_fit.times,
                 canada_fit.data,
                 c=settings.COLOURS["temperature"][canada_fit.name],
                 lw=2,
                 ls="--")
        ax4.text(1995, 0.8, "Canada, 244 lakes", fontsize=settings.FONTSIZE)

        # prettify
        for ax in [ax1, ax2, ax3, ax4]:
            ax.axhline(0, c='0.5', ls='--')
            utils.thicken_panel_border(ax)
            ax.set_ylim([-1, 1.2])
            ax.set_xlim([euro.times[0] - 1, int(settings.YEAR) + 1])
            ax.yaxis.set_ticks_position('left')
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
        for tick in ax4.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        fig.text(0.01,
                 0.35,
                 "Anomaly from 1996-2016 (" + r'$^\circ$' + "C)",
                 fontsize=settings.FONTSIZE,
                 rotation="vertical")
        fig.subplots_adjust(bottom=0.03, right=0.96, top=0.99, hspace=0.001)

        plt.savefig(settings.IMAGELOC + "LKT_ts{}".format(settings.OUTFMT))

        plt.close()

    #***************
    # Anomaly Scatter map
    if True:
        anomalies = read_lakes(DATALOC + "PlateX_data_LSWT.csv")

        bounds = [-8, -2, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2, 8]
        #        bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]

        lons = np.arange(-90, 120, 30)
        lats = np.arange(-180, 210, 30)
        dummy = np.ma.zeros((len(lats), len(lons)))
        dummy.mask = np.ones(dummy.shape)

        cube = utils.make_iris_cube_2d(dummy, lats, lons, "blank", "m")

        utils.plot_smooth_map_iris(settings.IMAGELOC + "LKT_anomaly", cube, settings.COLOURMAP_DICT["temperature"], \
                                       bounds, "Anomalies from 1996-2016 ("+r"$^{\circ}$"+"C)", \
                                       scatter=[anomalies[1], anomalies[0], anomalies[2]], figtext="", title="")

        utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_LKT_anomaly", cube, settings.COLOURMAP_DICT["temperature"], \
                                       bounds, "Anomalies from 1996-2016 ("+r"$^{\circ}$"+"C)", \
                                       scatter=[anomalies[1], anomalies[0], anomalies[2]], \
                                       figtext="(b) Lake Temperatures", title="")

    #***************
    # Insets Scatter map
    if True:

        fig = plt.figure(figsize=(8, 7))
        plt.clf()

        anomalies = read_lakes(DATALOC + "Fig2_data_LSWT.csv")

        bounds = [-8, -2, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2, 8]
        #        bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]
        cmap = settings.COLOURMAP_DICT["temperature"]
        norm = mpl.cm.colors.BoundaryNorm(bounds, cmap.N)
        this_cmap = copy.copy(cmap)

        # first_cube = iris.load(DATALOC + "amaps_1st_quarter_2018_250km.nc")[0]
        # third_cube = iris.load(DATALOC + "amaps_3rd_quarter_2018_250km.nc")[0]
        # annual_cube = iris.load(DATALOC + "amaps_annual_2018_250km.nc")[0]

        cube = iris.load(DATALOC + "lswt_anom_1979_2019.nc")[0]
        if settings.OUTFMT in [".eps", ".pdf"]:
            if cube.coord("latitude").points.shape[0] > 180 or cube.coord(
                    "longitude").points.shape[0] > 360:
                regrid_size = 1.0
                print("Regridding cube for {} output to {} degree resolution".
                      format(settings.OUTFMT, regrid_size))
                print("Old Shape {}".format(cube.data.shape))
                plot_cube = utils.regrid_cube(cube, regrid_size, regrid_size)
                print("New Shape {}".format(plot_cube.data.shape))
            else:
                plot_cube = copy.deepcopy(cube)
        else:
            plot_cube = copy.deepcopy(cube)

        # make axes by hand
        axes = ([0.01, 0.55, 0.59,
                 0.41], [0.565, 0.45, 0.47,
                         0.50], [0.01, 0.13, 0.59,
                                 0.41], [0.61, 0.07, 0.38,
                                         0.41], [0.1, 0.1, 0.8, 0.03])

        # Europe
        ax = plt.axes(axes[0], projection=cartopy.crs.PlateCarree())

        ax.gridlines()  #draw_labels=True)
        ax.add_feature(cartopy.feature.LAND,
                       zorder=0,
                       facecolor="0.9",
                       edgecolor="k")
        ax.coastlines(resolution="50m")
        #ax.add_feature(cartopy.feature.BORDERS.with_scale('110m'), linewidth=.5)
        ax.set_extent([-25, 40, 34, 72], cartopy.crs.PlateCarree())

        mesh = iris.plot.pcolormesh(plot_cube,
                                    cmap=this_cmap,
                                    norm=norm,
                                    axes=ax)
        plt.scatter(anomalies[1], anomalies[0], c=anomalies[2], cmap=this_cmap, norm=norm, s=25, \
                                transform=cartopy.crs.Geodetic(), edgecolor='0.1', linewidth=0.5, zorder=10)

        ax.text(0.05,
                1.05,
                "(a) Europe",
                fontsize=settings.FONTSIZE * 0.8,
                transform=ax.transAxes)
        utils.thicken_panel_border(ax)

        # Africa
        ax = plt.axes(axes[1], projection=cartopy.crs.PlateCarree())

        ax.gridlines()  #draw_labels=True)
        ax.add_feature(cartopy.feature.LAND,
                       zorder=0,
                       facecolor="0.9",
                       edgecolor="k")
        ax.coastlines(resolution="50m")
        #ax.add_feature(cartopy.feature.BORDERS.with_scale('110m'), linewidth=.5)
        ax.set_extent([-19, 43, -40, 33], cartopy.crs.PlateCarree())

        # lat_constraint = utils.latConstraint([25, 90])
        # nh_cube = third_cube.extract(lat_constraint)
        # lat_constraint = utils.latConstraint([-90, -25])
        # sh_cube = first_cube.extract(lat_constraint)
        # lat_constraint = utils.latConstraint([-25, 25])
        # trop_cube = annual_cube.extract(lat_constraint)

        # mesh = iris.plot.pcolormesh(nh_cube, cmap=this_cmap, norm=norm, axes=ax)
        # mesh = iris.plot.pcolormesh(trop_cube, cmap=this_cmap, norm=norm, axes=ax)
        # mesh = iris.plot.pcolormesh(sh_cube, cmap=this_cmap, norm=norm, axes=ax)
        mesh = iris.plot.pcolormesh(plot_cube,
                                    cmap=this_cmap,
                                    norm=norm,
                                    axes=ax)

        plt.scatter(anomalies[1], anomalies[0], c=anomalies[2], cmap=this_cmap, norm=norm, s=25, \
                                transform=cartopy.crs.Geodetic(), edgecolor='0.1', linewidth=0.5, zorder=10)

        ax.text(0.05,
                1.05,
                "(b) Africa",
                fontsize=settings.FONTSIZE * 0.8,
                transform=ax.transAxes)
        utils.thicken_panel_border(ax)

        # Canada
        ax = plt.axes(axes[2], projection=cartopy.crs.PlateCarree())

        ax.gridlines()  #draw_labels=True)
        ax.add_feature(cartopy.feature.LAND,
                       zorder=0,
                       facecolor="0.9",
                       edgecolor="k")
        ax.coastlines(resolution="50m")
        #ax.add_feature(cartopy.feature.BORDERS.with_scale('110m'), linewidth=.5)
        ax.set_extent([-140, -55, 42, 82], cartopy.crs.PlateCarree())

        mesh = iris.plot.pcolormesh(plot_cube,
                                    cmap=this_cmap,
                                    norm=norm,
                                    axes=ax)
        plt.scatter(anomalies[1], anomalies[0], c=anomalies[2], cmap=this_cmap, norm=norm, s=25, \
                                transform=cartopy.crs.Geodetic(), edgecolor='0.1', linewidth=0.5, zorder=10)

        ax.text(0.05,
                1.05,
                "(c) Canada",
                fontsize=settings.FONTSIZE * 0.8,
                transform=ax.transAxes)
        utils.thicken_panel_border(ax)

        # Tibet
        ax = plt.axes(axes[3], projection=cartopy.crs.PlateCarree())

        ax.gridlines()  #draw_labels=True)
        ax.add_feature(cartopy.feature.LAND,
                       zorder=0,
                       facecolor="0.9",
                       edgecolor="k")
        ax.coastlines(resolution="50m")
        ax.add_feature(cartopy.feature.BORDERS.with_scale('50m'), linewidth=.5)
        ax.set_extent([78, 102, 28, 39], cartopy.crs.PlateCarree())

        mesh = iris.plot.pcolormesh(plot_cube,
                                    cmap=this_cmap,
                                    norm=norm,
                                    axes=ax)
        plt.scatter(anomalies[1], anomalies[0], c=anomalies[2], cmap=this_cmap, norm=norm, s=25, \
                                transform=cartopy.crs.Geodetic(), edgecolor='0.1', linewidth=0.5, zorder=10)

        ax.text(0.05,
                1.05,
                "(d) Tibetan Plateau",
                fontsize=settings.FONTSIZE * 0.8,
                transform=ax.transAxes)
        utils.thicken_panel_border(ax)

        # colourbar
        cb = plt.colorbar(mesh,
                          cax=plt.axes(axes[4]),
                          orientation='horizontal',
                          ticks=bounds[1:-1],
                          drawedges=True)

        # prettify
        cb.ax.tick_params(axis='x',
                          labelsize=settings.FONTSIZE,
                          direction='in',
                          size=0)
        cb.set_label(label="Anomalies from 1996-2016 (" + r"$^{\circ}$" + "C)",
                     fontsize=settings.FONTSIZE)
        cb.set_ticklabels(["{:g}".format(b) for b in bounds[1:-1]])
        cb.outline.set_linewidth(2)
        cb.dividers.set_color('k')
        cb.dividers.set_linewidth(2)

        plt.savefig(settings.IMAGELOC +
                    "LKT_Regions_scatter_map{}".format(settings.OUTFMT))
        plt.close()
Пример #9
0
def plot_modis_ts(axl, sos, sprt, dummy, label, anomalies, legend_loc):

    utils.plot_ts_panel(axl, [sos, dummy], "-", "phenological", loc=legend_loc)

    # make twin
    axr = axl.twinx()
    utils.plot_ts_panel(axr, [sprt], "-", "phenological", loc="")

    # prettify
    axl.set_ylim([-10, 10])

    # labels
    axl.text(-0.17,
             1.08,
             label,
             transform=axl.transAxes,
             fontsize=settings.FONTSIZE)
    axl.text(0.4,
             0.88,
             anomalies[0],
             transform=axl.transAxes,
             fontsize=settings.FONTSIZE)
    axl.text(0.4,
             0.78,
             anomalies[1],
             transform=axl.transAxes,
             fontsize=settings.FONTSIZE)

    # ticks etc
    minorLocator = MultipleLocator(1)
    majorLocator = MultipleLocator(5)
    for ax in [axl]:
        if "EOS" in anomalies[0]:
            axr.set_ylim([-3, 3])
            ax.set_ylabel("EOS Anomaly (days)",
                          fontsize=settings.FONTSIZE,
                          color='g')
        elif "SOS" in anomalies[0]:
            axr.set_ylim([3, -3])
            ax.set_ylabel("SOS Anomaly (days)",
                          fontsize=settings.FONTSIZE,
                          color='g')
        ax.tick_params(axis='y', color='g')

    for ax in [axr]:
        ax.yaxis.tick_right()
        ax.set_ylabel("Temperature Anomaly (" + r'$^{\circ}$' + "C)",
                      fontsize=settings.FONTSIZE,
                      color='m')
        ax.tick_params(axis='y', color='m')
        ax.yaxis.set_tick_params(right=True,
                                 which="both",
                                 width=2,
                                 direction="in")

    for ax in [axl, axr]:
        utils.thicken_panel_border(ax)
        ax.set_yticks(ax.get_yticks()[1:-1])
        ax.xaxis.set_minor_locator(minorLocator)
        ax.xaxis.set_major_locator(majorLocator)
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
            tick.label2.set_fontsize(settings.FONTSIZE)
        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        ax.set_xlim([1999, int(settings.YEAR) + 1])

    return  # plot_modis_ts
Пример #10
0
def run_all_plots(download=False):

    if download:
        # download if required

        # AAO
        http("https://www.esrl.noaa.gov/", "psd/data/correlation", "aao.data", DATALOC, diagnostics=True)
        http("https://www.cpc.ncep.noaa.gov", "products/precip/CWlink/daily_ao_index/aao", "monthly.aao.index.b79.current.ascii", DATALOC, diagnostics=True)
        # AO
        http("https://www.cpc.ncep.noaa.gov", "products/precip/CWlink/daily_ao_index", "monthly.ao.index.b50.current.ascii", DATALOC, diagnostics=True)
        # NAO
        http("https://climatedataguide.ucar.edu", "sites/default/files", "nao_station_seasonal.txt", DATALOC, diagnostics=True)
        print("HadSLP2r & SOI likely to fail")
        # HadSLP2r
        http("http://www.metoffice.gov.uk", "hadobs/hadslp2/data", "hadslp2r.asc.gz", DATALOC, diagnostics=True)
        # SOI 
        doftp("ftp://ftp.bom.gov.au", "/anon/home/ncc/www/sco/soi/", "soiplaintext.html", DATALOC, diagnostics=True)

        print("Now check downloads")
        sys.exit()
    #************************************************************************
    # Timeseries figures - winter NAO
    #   initial run usually only Dec + Jan for recent year
    if True:
        # tried minor locator

        YEARS = ["2017", "2018", "2019"]
        plot_data, smoothed_data = read_winter_nao(DATALOC, YEARS)

        fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(8, 6.5))

        TEXTS = ["(d)", "(e)", "(f)"]
        for a, ax in enumerate([ax1, ax2, ax3]):
            year = int(YEARS[a])

            plt_bars(ax, plot_data[a], TEXTS[a], w=1, invert=False)
            utils.thicken_panel_border(ax)
            ax.xaxis.set_ticks([dt.datetime(year, 12, 1), dt.datetime(year+1, 1, 1), dt.datetime(year+1, 2, 1), dt.datetime(year+1, 3, 1)])

            ax.plot(plot_data[a].times+dt.timedelta(hours=12), smoothed_data[a], "k-", lw=LW)
            ax.set_xlim([dt.datetime(year, 11, 29), dt.datetime(year+1, 2, 1) + dt.timedelta(days=30)])

        ax3.xaxis.set_ticklabels(["Dec", "Jan", "Feb", "Mar"], fontsize=settings.FONTSIZE)
        ax2.set_ylabel("Winter NAO Index (hPa)", fontsize=settings.FONTSIZE)

        fig.subplots_adjust(right=0.98, top=0.98, bottom=0.05, hspace=0.001)
        plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)

        for ax in [ax1, ax2, ax3]:
            ax.set_ylim([-69, 99])
            ax.yaxis.set_ticks_position('left')

            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

        plt.savefig(settings.IMAGELOC+"SLP_ts_winter_nao{}".format(settings.OUTFMT))
        plt.close()

    #************************************************************************
    # Timeseries figures - different indices
    if True:
        SOI = read_soi(DATALOC + "soiplaintext.html")
        AO = read_a_ao(DATALOC + "monthly.ao.index.b50.current.ascii", "AO", 3)
        AAO = read_a_ao(DATALOC + "monthly.aao.index.b79.current.ascii", "AAO", 5)
    #    SNAO = read_snao(DATALOC + "JA STANDARDISED SNAO.txt") # from Chris Folland - unavailable in 2019
        NAO = read_nao(DATALOC + "nao_station_seasonal.txt")

        fig = plt.figure(figsize=(8, 6))

        # manually set up the 10 axes
        w = 0.42
        h = 0.23
        c = 0.51
        ax1 = plt.axes([c-w, 0.99-h, w, h])
        ax2 = plt.axes([c, 0.99-h, w, h])
        ax3 = plt.axes([c-w, 0.99-(2*h), w, h], sharex=ax1)
        ax4 = plt.axes([c, 0.99-(2*h), w, h], sharex=ax2)
        ax5 = plt.axes([c-w, 0.99-(3*h), w, h], sharex=ax1)
        ax6 = plt.axes([c, 0.99-(3*h), w, h], sharex=ax2)
        ax7 = plt.axes([c-w, 0.99-(4*h), w, h], sharex=ax1)
        ax8 = plt.axes([c, 0.99-(4*h), w, h], sharex=ax2)
    #    ax9 = plt.axes([c-w, 0.99-(5*h), w, h], sharex=ax1)
    #    ax10= plt.axes([c, 0.99-(5*h), w, h], sharex=ax2)

        plt_bars(ax1, SOI, "(a)", w=1./12, invert=True)
        plt_bars(ax3, AO, "(c)", w=1./12)
        plt_bars(ax5, AAO, "(e)", w=1./12)
        plt_bars(ax7, NAO, "(g)", w=1.)
    #    plt_bars(ax9, SNAO, "(i)", w=1.)

        ax1.set_xlim([1860, int(settings.YEAR)+1])

        plt_bars(ax2, SOI, "(b)", w=1./12, invert=True)
        plt_bars(ax4, AO, "(d)", w=1./12)
        plt_bars(ax6, AAO, "(f)", w=1./12)
        plt_bars(ax8, NAO, "(h)", w=0.9)
    #    plt_bars(ax10, SNAO, "(j)", w=0.9)

        ax2.set_xlim([2006, int(settings.YEAR)+2])
        for ax in [ax2, ax4, ax6, ax8]:#, ax10]:
            ax.yaxis.tick_right()

        # prettify
        for ax in [ax1, ax3, ax5, ax7]:#, ax9]:
            for tick in ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
            utils.thicken_panel_border(ax)
            ax.yaxis.set_ticks_position('left')

        for ax in [ax2, ax4, ax6, ax8]:#, ax10]:
            for tick in ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
            ax.yaxis.tick_right()
            for tick in ax.yaxis.get_major_ticks():
                tick.label2.set_fontsize(settings.FONTSIZE)
            utils.thicken_panel_border(ax)

        plt.setp([a.get_xticklabels() for a in fig.axes[:-2]], visible=False)

        ax1.xaxis.set_ticks([1880, 1920, 1960, 2000])
        ax2.xaxis.set_ticks([2007, 2010, 2013, 2016, 2019])
        ax1.yaxis.set_ticks([-40, 0, 40])
        ax2.yaxis.set_ticks([-40, 0, 40])
        ax3.yaxis.set_ticks([-4, 0, 4])
        ax4.yaxis.set_ticks([-4, 0, 4])
        ax5.yaxis.set_ticks([-2, 0, 2])
        ax6.yaxis.set_ticks([-2, 0, 2])
        ax7.yaxis.set_ticks([-4, 0, 4])
        ax8.yaxis.set_ticks([-4, 0, 4])
    #    ax9.yaxis.set_ticks([-2, 0, 2])
    #    ax10.yaxis.set_ticks([-2, 0, 2])

        minorLocator = MultipleLocator(1)
        ax2.xaxis.set_minor_locator(minorLocator)

        ax1.set_ylim([-40, 45])
        ax2.set_ylim([-40, 45])
        ax3.set_ylim([-4.5, 4.9])
        ax4.set_ylim([-4.5, 4.9])

        ax5.set_ylabel("Standard Units", fontsize=settings.FONTSIZE)

        plt.savefig(settings.IMAGELOC+"SLP_ts{}".format(settings.OUTFMT))

        plt.close()

    #************************************************************************
    # Global map
    if True:
        cube = read_hadslp(DATALOC + "hadslp2r.asc")

        # restrict to 1900 to last full year
        date_constraint = utils.periodConstraint(cube, dt.datetime(1900, 1, 1), dt.datetime(int(settings.YEAR)+1, 1, 1)) 
        cube = cube.extract(date_constraint)

        # convert to 1981-2010 climatology.
        clim_constraint = utils.periodConstraint(cube, dt.datetime(1981, 1, 1), dt.datetime(2011, 1, 1)) 
        clim_cube = cube.extract(clim_constraint)

        clim_data = clim_cube.data.reshape(-1, 12, clim_cube.data.shape[-2], clim_cube.data.shape[-1])

        # more than 15 years present
        climatology = np.ma.mean(clim_data, axis=0)
        nyears = np.ma.count(clim_data, axis=0)
        climatology = np.ma.masked_where(nyears <= 15, climatology) # Kate keeps GT 15.


        # extract final year
        final_year_constraint = utils.periodConstraint(cube, dt.datetime(int(settings.YEAR), 1, 1), dt.datetime(int(settings.YEAR)+1, 1, 1)) 
        final_year_cube = cube.extract(final_year_constraint)

        final_year_cube.data = final_year_cube.data - climatology

        # more than 6 months present
        annual_cube = final_year_cube.collapsed(['time'], iris.analysis.MEAN)
        nmonths = np.ma.count(final_year_cube.data, axis=0)
        annual_cube.data = np.ma.masked_where(nmonths <= 6, annual_cube.data)

        bounds = [-100, -8, -4, -2, -1, 0, 1, 2, 4, 8, 100]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "SLP_{}_anoms_hadslp".format(settings.YEAR), annual_cube, settings.COLOURMAP_DICT["circulation"], bounds, "Anomalies from 1981-2010 (hPa)")
        utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_SLP_{}_anoms_hadslp".format(settings.YEAR), annual_cube, settings.COLOURMAP_DICT["circulation"], bounds, "Anomalies from 1981-2010 (hPa)", figtext="(u) Sea Level Pressure")

        plt.close()

        del annual_cube
        del final_year_cube
        gc.collect()

    #************************************************************************
    # Polar Figures (1x3)
    if True:
        # apply climatology - incomplete end year, so repeat climatology and then trunkate
        climatology = np.tile(climatology, ((cube.data.shape[0]//12)+1, 1, 1))
        anoms = iris.cube.Cube.copy(cube)

        anoms.data = anoms.data - climatology[0:anoms.data.shape[0], :, :]

        bounds = [-100, -8, -4, -2, -1, -0.5, 0.5, 1, 2, 4, 8, 100]

        # set up a 1 x 3 set of axes
        fig = plt.figure(figsize=(4, 9.5))
        plt.clf()

        # set up plot settings
        cmap = settings.COLOURMAP_DICT["circulation"]
        norm = mpl.cm.colors.BoundaryNorm(bounds, cmap.N)
        PLOTYEARS = [2017, 2018, 2019]
        PLOTLABELS = ["(a) 2017/18", "(b) 2018/19", "(c) 2019/20"]

        # boundary circle
        theta = np.linspace(0, 2*np.pi, 100)
        center, radius = [0.5, 0.5], 0.5
        verts = np.vstack([np.sin(theta), np.cos(theta)]).T
        circle = mpath.Path(verts * radius + center)


        # spin through axes
        for a in range(3):  

            ax = plt.subplot(3, 1, a+1, projection=cartopy.crs.NorthPolarStereo())

            plot_cube = iris.cube.Cube.copy(anoms)

            # extract 3 winter months
            date_constraint = utils.periodConstraint(anoms, dt.datetime(PLOTYEARS[a], 12, 1), dt.datetime(PLOTYEARS[a]+1, 3, 1)) 
            plot_cube = plot_cube.extract(date_constraint)

            # plot down to (almost) equator
            lat_constraint = utils.latConstraint([3, 80]) 
            plot_cube = plot_cube.extract(lat_constraint)

            # take the mean
            try:
                plot_cube = plot_cube.collapsed(['time'], iris.analysis.MEAN)
            except iris.exceptions.CoordinateCollapseError:
                pass

            ax.gridlines() #draw_labels=True)
            ax.add_feature(cartopy.feature.LAND, zorder=0, facecolor="0.9", edgecolor="k")
            ax.coastlines()
            ax.set_boundary(circle, transform=ax.transAxes)
            ax.set_extent([-180, 180, 0, 90], cartopy.crs.PlateCarree())

            ext = ax.get_extent() # save the original extent

            mesh = iris.plot.pcolormesh(plot_cube, cmap=cmap, norm=norm, axes=ax)

            ax.set_extent(ext, ax.projection) # fix the extent change from colormesh
            ax.text(0.0, 1.02, PLOTLABELS[a], fontsize=settings.FONTSIZE, transform=ax.transAxes)

        # add a colourbar for the figure
        cbar_ax = fig.add_axes([0.77, 0.07, 0.04, 0.9])
        cb = plt.colorbar(mesh, cax=cbar_ax, orientation='vertical', ticks=bounds[1:-1], drawedges=True)
        cb.ax.tick_params(axis='y', labelsize=settings.FONTSIZE, direction='in', size=0)
        cb.set_label(label="Anomaly (hPa)", fontsize=settings.FONTSIZE)

        # prettify
        cb.set_ticklabels(["{:g}".format(b) for b in bounds[1:-1]])
        cb.outline.set_linewidth(2)
        cb.dividers.set_color('k')
        cb.dividers.set_linewidth(2)


        fig.subplots_adjust(bottom=0.01, top=0.97, left=0.01, right=0.8, wspace=0.02)

        plt.title("")
        fig.text(0.03, 0.95, "", fontsize=settings.FONTSIZE * 0.8)

        plt.savefig(settings.IMAGELOC + "SLP_polar{}".format(settings.OUTFMT))
        plt.close()

        del plot_cube
        del climatology
        gc.collect()

        #************************************************************************
        # SNAO figures
        if False:
            date_constraint = utils.periodConstraint(anoms, dt.datetime(int(settings.YEAR), 7, 1), dt.datetime(int(settings.YEAR), 9, 1)) 
            ja_cube = anoms.extract(date_constraint)
            ja_cube = ja_cube.collapsed(['time'], iris.analysis.MEAN)

            bounds = [-100, -4, -3, -2, -1, 0, 1, 2, 3, 4, 100]
            cmap = settings.COLOURMAP_DICT["circulation"]
            norm = mpl.cm.colors.BoundaryNorm(bounds, cmap.N)
            PLOTLABEL = "(a) July - August"

            fig = plt.figure(figsize=(8, 10))
            plt.clf()
            # make axes by hand
            axes = ([0.05, 0.45, 0.9, 0.55], [0.1, 0.05, 0.88, 0.35])

            ax = plt.axes(axes[0], projection=cartopy.crs.Robinson())

            ax.gridlines() #draw_labels=True)
            ax.add_feature(cartopy.feature.LAND, zorder=0, facecolor="0.9", edgecolor="k")
            ax.coastlines()

            mesh = iris.plot.pcolormesh(ja_cube, cmap=cmap, norm=norm, axes=ax)

            ax.text(-0.05, 1.05, PLOTLABEL, fontsize=settings.FONTSIZE * 0.8, transform=ax.transAxes)

            # colorbar
            cb = plt.colorbar(mesh, orientation='horizontal', ticks=bounds[1:-1], label="Anomaly (hPa)", drawedges=True, pad=0.05)

            # prettify
            cb.set_ticklabels(["{:g}".format(b) for b in bounds[1:-1]])
            cb.outline.set_linewidth(2)
            cb.dividers.set_color('k')
            cb.dividers.set_linewidth(2)

            # and the timeseries
            ax = plt.axes(axes[1])

            snao = np.genfromtxt(DATALOC+"{} DAILY SNAO.txt".format(settings.YEAR), dtype=(float))

            data = snao[:, 1]
            times = np.array([dt.datetime(int(settings.YEAR), 7, 1) + dt.timedelta(days=i) for i in range(len(data))])

            SNAO = utils.Timeseries("Summer NAO Index", times, data)

            plt_bars(ax, SNAO, "", w=0.7, label=False)
            ax.text(-0.1, 1.05, "(b) Summer NAO Index", fontsize=settings.FONTSIZE * 0.8, transform=ax.transAxes)
            ax.yaxis.set_label("Summer NAO Index")
            # label every 14 days
            ticks = [dt.datetime(int(settings.YEAR), 7, 1) + dt.timedelta(days=i) for i in range(0, len(data), 14)]
            ax.xaxis.set_ticks(ticks)
            ax.xaxis.set_ticklabels([dt.datetime.strftime(t, "%d %b %Y") for t in ticks])
            minorLocator = MultipleLocator(1)
            ax.xaxis.set_minor_locator(minorLocator)

            utils.thicken_panel_border(ax3)

            plt.savefig(settings.IMAGELOC + "SLP_SNAO{}".format(settings.OUTFMT))
            plt.close()

            del ja_cube
            gc.collect()

        #************************************************************************
        # EU figure
        if False:
            contour = True

            date_constraint = utils.periodConstraint(anoms, dt.datetime(int(settings.YEAR), 7, 1), dt.datetime(int(settings.YEAR), 8, 1)) 
            jul_cube = anoms.extract(date_constraint)
            date_constraint = utils.periodConstraint(anoms, dt.datetime(int(settings.YEAR), 8, 1), dt.datetime(int(settings.YEAR), 9, 1)) 
            aug_cube = anoms.extract(date_constraint)

            bounds = [-100, -4, -3, -2, -1, 0, 1, 2, 3, 4, 100]
            cmap = settings.COLOURMAP_DICT["circulation"]
            norm = mpl.cm.colors.BoundaryNorm(bounds, cmap.N)
            PLOTLABELS = ["(a) July", "(b) August"]

            fig = plt.figure(figsize=(8, 14))
            plt.clf()
            # make axes by hand
            axes = ([0.1, 0.65, 0.8, 0.3], [0.1, 0.35, 0.8, 0.3], [0.1, 0.05, 0.8, 0.25])

            cube_list = [jul_cube, aug_cube]
            for a in range(2):
                ax = plt.axes(axes[a], projection=cartopy.crs.PlateCarree(central_longitude=-10))

                ax.gridlines() #draw_labels=True)
                ax.add_feature(cartopy.feature.LAND, zorder=0, facecolor="0.9", edgecolor="k")
                ax.coastlines()
                ax.set_extent([-70, 40, 30, 80], cartopy.crs.PlateCarree())

                if contour:
                    from scipy.ndimage.filters import gaussian_filter
                    sigma = 0.5
                    cube = cube_list[a]

                    cube.data = gaussian_filter(cube.data, sigma)
                    mesh = iris.plot.contourf(cube, bounds, cmap=cmap, norm=norm, axes=ax)

                else:
                    mesh = iris.plot.pcolormesh(cube_list[a], cmap=cmap, norm=norm, axes=ax)

                ax.text(-0.05, 1.05, PLOTLABELS[a], fontsize=settings.FONTSIZE * 0.8, transform=ax.transAxes)

            # colorbar
            cb = plt.colorbar(mesh, orientation='horizontal', ticks=bounds[1:-1], label="Anomaly (hPa)", drawedges=True)

            # prettify
            cb.set_ticklabels(["{:g}".format(b) for b in bounds[1:-1]])
            cb.outline.set_linewidth(2)
            cb.dividers.set_color('k')
            cb.dividers.set_linewidth(2)

            # and the timeseries
            ax3 = plt.axes(axes[2])

            snao = np.genfromtxt(DATALOC+"{} DAILY SNAO.txt".format(settings.YEAR), dtype=(float))

            data = snao[:, 1]
            times = np.array([dt.datetime(int(settings.YEAR), 7, 1) + dt.timedelta(days=i) for i in range(len(data))])

            SNAO = utils.Timeseries("Summer NAO Index", times, data)

            plt_bars(ax3, SNAO, "", w=0.7, label=False)
            ax3.text(-0.05, 1.05, "(c) Summer NAO Index", fontsize=settings.FONTSIZE * 0.8, transform=ax3.transAxes)
            ax3.yaxis.set_label("Summer NAO Index")
            # label every 14 days
            ticks = [dt.datetime(int(settings.YEAR), 7, 1) + dt.timedelta(days=i) for i in range(0, len(data), 14)]
            ax3.xaxis.set_ticks(ticks)
            ax3.xaxis.set_ticklabels([dt.datetime.strftime(t, "%d %b %Y") for t in ticks])
            minorLocator = MultipleLocator(1)
            ax3.xaxis.set_minor_locator(minorLocator)
            ax3.yaxis.set_ticks_position('left')

            utils.thicken_panel_border(ax3)

            plt.savefig(settings.IMAGELOC + "SLP_NAtlantic{}".format(settings.OUTFMT))
            plt.close()

            del cube
            del anoms
            gc.collect()


    return # run_all_plots
Пример #11
0
def run_all_plots():

    #************************************************************************
    # Timeseries
    if True:

        IRdata = read_binary_ts(
            DATALOC +
            "TimeseriesBHRNIR_C7_poids_{}.bin".format(int(settings.YEAR) + 1))
        Vdata = read_binary_ts(
            DATALOC +
            "TimeseriesBHRV_C7_poids_{}.bin".format(int(settings.YEAR) + 1))

        fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6.5), sharex=True)
        COLOURS = settings.COLOURS["land_surface"]

        for dataset in Vdata:
            print(dataset.name)
            locs, = np.where(dataset.data != 0)
            ls = "--"
            lw = 1
            if dataset.name.split(" ")[-1] == "Smoothed":
                ls = "-"
                lw = 2
            ax1.plot(dataset.times[locs],
                     dataset.data[locs],
                     c=COLOURS[dataset.name],
                     ls=ls,
                     label=dataset.name,
                     lw=lw)

        ax1.axhline(0, c='0.5', ls='--')
        utils.thicken_panel_border(ax1)

        for dataset in IRdata:
            print(dataset.name)
            locs, = np.where(
                dataset.data != 0)  # remove zero bits (mainly for smoothed)
            ls = "--"
            lw = 1
            if dataset.name.split(" ")[-1] == "Smoothed":
                ls = "-"
                lw = 2
            ax2.plot(dataset.times[locs],
                     dataset.data[locs],
                     c=COLOURS[dataset.name],
                     ls=ls,
                     label=dataset.name,
                     lw=lw)

        ax2.legend(loc=LEGEND_LOC,
                   ncol=2,
                   frameon=False,
                   prop={'size': settings.LEGEND_FONTSIZE * 0.8},
                   labelspacing=0.1,
                   columnspacing=0.5)
        ax2.axhline(0, c='0.5', ls='--')
        utils.thicken_panel_border(ax2)

        #*******************
        # prettify

        fig.text(0.01,
                 0.5,
                 "Normalized Anomalies (%)",
                 va='center',
                 rotation='vertical',
                 fontsize=settings.FONTSIZE)

        plt.xlim([2002.5, int(settings.YEAR) + 1.5])
        ax2.set_ylim([-5.8, None])
        for ax in [ax1, ax2]:
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
            ax.xaxis.set_minor_locator(minorLocator)
            ax.set_yticks(ax.get_yticks()[1:-1])
            ax.yaxis.set_ticks_position('left')
        for tick in ax2.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        ax1.text(0.02,
                 0.9,
                 "(a) Visible",
                 transform=ax1.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax2.text(0.02,
                 0.9,
                 "(b) Near Infrared",
                 transform=ax2.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)

        fig.subplots_adjust(right=0.95, top=0.95, bottom=0.05, hspace=0.001)

        plt.savefig(settings.IMAGELOC + "ABD_ts{}".format(settings.OUTFMT))
        plt.close()

    #************************************************************************
    # Hovmullers
    if True:
        IRdata = read_binary(
            DATALOC +
            "HovMullerBHRNIR_C7_{}.bin".format(int(settings.YEAR) + 1))
        Vdata = read_binary(
            DATALOC + "HovMullerBHRV_C7_{}.bin".format(int(settings.YEAR) + 1))

        # reshape - from Readme
        IRdata = IRdata.reshape(360, DURATION)
        Vdata = Vdata.reshape(360, DURATION)

        IRdata = np.ma.masked_where(IRdata <= -100.,
                                    IRdata)  # * 100 # from readme
        Vdata = np.ma.masked_where(Vdata <= -100., Vdata)  # * 100

        lats = np.arange(-90, 90, 0.5)

        # curtail times
        locs, = np.where(times > int(settings.YEAR) + 1)
        IRdata.mask[:, locs] = True
        Vdata.mask[:, locs] = True
        times.mask[locs] = True

        # cant use "cmap.set_bad" for contour as ignored when contouring

        bounds = [-100, -20, -15, -10, -5, -1, 1, 5, 10, 15, 20, 100]
        utils.plot_hovmuller(settings.IMAGELOC + "ABD_NIR_hovmuller",
                             times,
                             lats,
                             IRdata,
                             settings.COLOURMAP_DICT["land_surface_r"],
                             bounds,
                             "Normalized Anomalies (%)",
                             figtext="(b)",
                             background="0.7")
        utils.plot_hovmuller(settings.IMAGELOC + "ABD_V_hovmuller",
                             times,
                             lats,
                             Vdata,
                             settings.COLOURMAP_DICT["land_surface_r"],
                             bounds,
                             "Normalized Anomalies (%)",
                             figtext="(a)",
                             background="0.7")

    #************************************************************************
    # Anomalies
    if True:
        IRdata = read_binary(
            DATALOC + "Annual_BHRNIR_C7_{}.bin".format(int(settings.YEAR) + 1))
        Vdata = read_binary(
            DATALOC + "Annual_BHRV_C7_{}.bin".format(int(settings.YEAR) + 1))

        # reshape - from Readme
        IRdata = IRdata.reshape(360, 720)
        Vdata = Vdata.reshape(360, 720)

        IRdata = np.ma.masked_where(IRdata <= -9999., IRdata)
        Vdata = np.ma.masked_where(Vdata <= -9999., Vdata)

        IRdata = np.ma.masked_where(IRdata == 0., IRdata)
        Vdata = np.ma.masked_where(Vdata == 0., Vdata)

        delta = 0.5
        lons = np.arange(-180 + (delta / 2.), 180, delta)
        lats = np.arange(-90 + (delta / 2.), 90, delta)

        ir_cube = utils.make_iris_cube_2d(IRdata, lats, lons, "IR Albedo", "%")
        v_cube = utils.make_iris_cube_2d(Vdata, lats, lons, "V Albedo", "%")

        bounds = [-100, -20, -15, -10, -5, 0, 5, 10, 15, 20, 100]

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "p2.1_ABD_V_{}".format(settings.YEAR),
            v_cube,
            settings.COLOURMAP_DICT["land_surface_r"],
            bounds,
            "Anomalies from 2003-{} (%)".format(2010),
            figtext="(ac) Land Surface Albedo in the Visible")
        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "ABD_V_{}".format(settings.YEAR), v_cube,
            settings.COLOURMAP_DICT["land_surface_r"], bounds,
            "Anomalies from 2003-{} (%)".format(2010))

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "p2.1_ABD_NIR_{}".format(settings.YEAR),
            ir_cube,
            settings.COLOURMAP_DICT["land_surface_r"],
            bounds,
            "Anomalies from 2003-{} (%)".format(2010),
            figtext="(ad) Land Surface Albedo in the Near Infrared")
        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "ABD_NIR_{}".format(settings.YEAR), ir_cube,
            settings.COLOURMAP_DICT["land_surface_r"], bounds,
            "Anomalies from 2003-{} (%)".format(2010))

    return  # run_all_plots
Пример #12
0
def run_all_plots():

    #************************************************************************
    # Cloudiness timeseries
    if True:
        plt.clf()
        fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6.5), sharex=True)

        infilename = os.path.join(
            DATALOC,
            "{}_global_cloudiness_timeseries_v2.txt".format(settings.YEAR))

        # anomalies
        patmosx, hirs, misr, modis, calipso, ceres, satcorps, clara_a2, patmosdx, cci = \
            read_ts(infilename, anomaly=True)

        utils.plot_ts_panel(ax1, [
            patmosx, hirs, misr, modis, calipso, ceres, satcorps, clara_a2,
            patmosdx, cci
        ],
                            "-",
                            "hydrological",
                            loc="")

        ax1.text(0.02,
                 0.9,
                 "(a) Satellite - Anomalies",
                 transform=ax1.transAxes,
                 fontsize=settings.FONTSIZE)

        # actuals
        patmosx, hirs, misr, modis, calipso, ceres, satcorps, clara_a2, patmosdx, cci = \
            read_ts(infilename)

        utils.plot_ts_panel(ax2, [
            patmosx, hirs, misr, modis, calipso, ceres, satcorps, clara_a2,
            patmosdx, cci
        ],
                            "-",
                            "hydrological",
                            loc=LEGEND_LOC,
                            ncol=3)

        ax2.text(0.02,
                 0.9,
                 "(b) Satellite - Actual",
                 transform=ax2.transAxes,
                 fontsize=settings.FONTSIZE)

        #*******************
        # prettify
        ax1.set_ylabel("Anomaly (%)", fontsize=settings.FONTSIZE)
        ax2.set_ylabel("(%)", fontsize=settings.FONTSIZE)

        for tick in ax2.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        minorLocator = MultipleLocator(1)
        for ax in [ax1, ax2]:
            utils.thicken_panel_border(ax)
            ax.set_yticks(ax.get_yticks()[1:])
            ax.xaxis.set_minor_locator(minorLocator)
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

        plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)
        fig.subplots_adjust(right=0.96,
                            top=0.99,
                            bottom=0.04,
                            left=0.09,
                            hspace=0.001)

        plt.xlim([hirs.times[0] - 1, hirs.times[-1] + 1])
        ax1.set_ylim([-4.4, 6.9])
        ax2.set_ylim([0, 95])

        plt.savefig(settings.IMAGELOC + "CLD_ts{}".format(settings.OUTFMT))
        plt.close()

    #************************************************************************
    # make a version using the full base period of the data and only the pre2000 datasets
    if False:
        plt.clf()
        fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6.5), sharex=True)

        # anomalies
        patmosx, hirs, misr, modis, calipso, ceres, satcorps, clara_a2, patmosdx, cci = \
            read_ts(DATALOC + "{}_global_cloudiness_timeseries.txt".format(settings.YEAR), \
                        anomaly=True, fullbase=True)

        utils.plot_ts_panel(ax1, [patmosx, hirs, satcorps, clara_a2, cci],
                            "-",
                            "hydrological",
                            loc="")

        ax1.text(0.02,
                 0.9,
                 "(a) Satellite - Anomalies",
                 transform=ax1.transAxes,
                 fontsize=settings.FONTSIZE)

        # actuals
        patmosx, hirs, misr, modis, calipso, ceres, satcorps, clara_a2, patmosdx, cci = \
            read_ts(DATALOC + "{}_global_cloudiness_timeseries.txt".format(settings.YEAR))

        utils.plot_ts_panel(ax2, [patmosx, hirs, satcorps, clara_a2, cci], "-", "hydrological", \
                                loc=LEGEND_LOC, ncol=3)

        ax2.text(0.02,
                 0.9,
                 "(b) Satellite - Actual",
                 transform=ax2.transAxes,
                 fontsize=settings.FONTSIZE)

        #*******************
        # prettify
        ax1.set_ylabel("Anomaly (%)", fontsize=settings.FONTSIZE)
        ax2.set_ylabel("(%)", fontsize=settings.FONTSIZE)

        for tick in ax2.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        minorLocator = MultipleLocator(1)
        for ax in [ax1, ax2]:
            utils.thicken_panel_border(ax)
            ax.set_yticks(ax.get_yticks()[1:])
            ax.xaxis.set_minor_locator(minorLocator)
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

        plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)
        fig.subplots_adjust(right=0.95, top=0.95, hspace=0.001)

        plt.xlim([hirs.times[0] - 1, hirs.times[-1] + 1])
        ax1.set_ylim([-4.9, 4.4])
        ax2.set_ylim([0, 95])

        plt.savefig(settings.IMAGELOC +
                    "CLD_ts_fullbaseperiod{}".format(settings.OUTFMT))
        plt.close()

    #************************************************************************
    # Cloudiness map
    if True:
        mapfile_dict = scipy.io.readsav(
            DATALOC +
            "patmosx_global_monthly_cloudiness_anomaly_map_{}.sav".format(
                settings.YEAR))

        annual_anoms = mapfile_dict["annual_anom"] * 100.
        djf_anoms = mapfile_dict["djf_anom"] * 100.
        jja_anoms = mapfile_dict["jja_anom"] * 100.
        mam_anoms = mapfile_dict["mam_anom"] * 100.
        son_anoms = mapfile_dict["son_anom"] * 100.

        lats = mapfile_dict["lat"]
        lons = mapfile_dict["lon"]

        cube = utils.make_iris_cube_2d(annual_anoms, lats[:, 0], lons[0],
                                       "CLD_anom", "%")

        bounds = [-100, -15, -10, -5, -2.5, 0, 2.5, 5, 10, 15, 100]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "CLD_{}_anoms".format(settings.YEAR), cube, \
                                       settings.COLOURMAP_DICT["hydrological"], bounds, \
                                       "Anomalies from 1981-2010 (%)")
        utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_CLD_{}_anoms".format(settings.YEAR), \
                                       cube, settings.COLOURMAP_DICT["hydrological"], bounds, \
                                       "Anomalies from 1981-2010 (%)", figtext="(n) Cloudiness")

    #************************************************************************
    # Cloudiness Seasonal Map
    if True:
        cubelist = []
        for season in [djf_anoms, mam_anoms, jja_anoms, son_anoms]:

            cube = utils.make_iris_cube_2d(season, lats[:, 0], lons[0],
                                           "CLD_anom", "%")
            cubelist += [cube]


        utils.plot_smooth_map_iris_multipanel(settings.IMAGELOC + "CLD_{}_anoms_seasons".format(settings.YEAR), \
                                                  cubelist, settings.COLOURMAP_DICT["hydrological"], \
                                                  bounds, "Anomaly (%)", shape=(2, 2), \
                                                  title=["DJF", "MAM", "JJA", "SON"], \
                                                  figtext=["(a)", "(b)", "(c)", "(d)"])

    #************************************************************************
    # Cloudiness Hovmoller
    if True:
        data_dict = scipy.io.readsav(
            DATALOC +
            "patmosx_global_monthly_cloudiness_hovmuller_{}.sav".format(
                settings.YEAR))

        lats = data_dict["latitude"]
        times = data_dict["hov_time"]
        anoms = data_dict["hov_anom"] * 100.

        utils.plot_hovmuller(settings.IMAGELOC + "CLD_hovmuller", times, lats,
                             anoms, settings.COLOURMAP_DICT["hydrological"],
                             bounds, "Anomaly (%)")

    return  # run_all_plots
Пример #13
0
def run_all_plots():

    # # CEI timeseries
    if True:
        # from https://www.ncdc.noaa.gov/extremes/cei/graph/us/03-05/4 (Spring, Step4 indicator)
        cei = read_cei("CEI_step4_figure_data.csv")
        smoothed = binomialfilter(cei.data, -99.9, 9, pad=False)
        smoothed = np.ma.masked_where(smoothed == -99.9, smoothed)

        fig = plt.figure(figsize=(8, 5))
        plt.clf()
        ax1 = plt.axes([0.11, 0.08, 0.86, 0.90])

        ax1.bar(cei.times,
                cei.data,
                color="g",
                label=cei.name,
                align="center",
                width=1,
                edgecolor="darkgreen")
        ax1.plot(cei.times, smoothed, "r", lw=LW)

        ax1.plot([cei.times[0], cei.times[-1]],
                 [np.mean(cei.data), np.mean(cei.data)],
                 "k",
                 lw=1)

        ax1.set_xlim([1910, int(settings.YEAR) + 2])
        ax1.set_ylabel("%", fontsize=settings.FONTSIZE)
        minorLocator = MultipleLocator(1)
        ax1.xaxis.set_minor_locator(minorLocator)

        utils.thicken_panel_border(ax1)
        ax1.yaxis.set_tick_params(right=False)
        for tick in ax1.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for tick in ax1.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

#        ax1.text(0.02, 0.9, "(e)", transform=ax1.transAxes, fontsize=settings.FONTSIZE)
        plt.savefig(settings.IMAGELOC + "PEX_CEI_ts{}".format(settings.OUTFMT))

        plt.close()

    #*************************
    # GHCNDEX indices
    rank_bounds = [-4.5, -3.5, -2.5, -1.5, 1.5, 2.5, 3.5, 4.5]

    if True:

        for index in ETCCDI_INDICES:

            cube_list = iris.load(
                DATALOC +
                "GHCND_{}_1951-{}_RegularGrid_global_2.5x2.5deg_LSmask.nc".
                format(index,
                       int(settings.YEAR) + 1))
            names = np.array([cube.name() for cube in cube_list])

            #*************
            # plot annual map

            selected_cube, = np.where(names == "Ann")

            total_cube = cube_list[selected_cube[0]]
            total_cube.coord('latitude').guess_bounds()
            total_cube.coord('longitude').guess_bounds()

            anoms = copy.deepcopy(total_cube)
            anoms = ApplyClimatology(anoms)

            # select the year to plot
            years = GetYears(total_cube)
            loc, = np.where(years == SELECTED_YEAR)

            # sort the bounds and colourbars
            if index in ["Rx1day"]:
                bounds = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
                cmap = settings.COLOURMAP_DICT["precip_sequential"]
            elif index in ["Rx5day"]:
                bounds = [0, 20, 40, 60, 80, 100, 120, 140, 160, 180]
                cmap = settings.COLOURMAP_DICT["precip_sequential"]
            elif index in ["R10mm"]:
                bounds = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45]
                cmap = settings.COLOURMAP_DICT["precip_sequential"]
            elif index in ["R20mm"]:
                bounds = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45]
                cmap = settings.COLOURMAP_DICT["precip_sequential"]
            elif index in ["R95p"]:
                bounds = [0, 25, 50, 75, 100, 125, 150, 175, 200, 225]
                cmap = settings.COLOURMAP_DICT["precip_sequential"]
            elif index in ["PRCPTOT"]:
                bounds = [0, 25, 50, 75, 100, 125, 150, 200, 300, 400]
                cmap = settings.COLOURMAP_DICT["precip_sequential"]

            utils.plot_smooth_map_iris(
                settings.IMAGELOC +
                "PEX_{}_{}_ghcndex".format(index, settings.YEAR),
                total_cube[loc[0]],
                cmap,
                bounds,
                "{} ({})".format(index, ETCCDI_UNITS[index]),
                title="GHCNDEX {} - {}".format(index, ETCCDI_LABELS[index]))

            # sort the bounds and colourbars
            if index in ["Rx1day"]:
                bounds = [-100, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 100]
                bounds = [
                    -100, -40, -30, -20, -10, -5, 0, 5, 10, 20, 30, 40, 100
                ]
                cmap = settings.COLOURMAP_DICT["hydrological"]
            elif index in ["Rx5day"]:
                bounds = [
                    -100, -40, -30, -20, -10, -5, 0, 5, 10, 20, 30, 40, 100
                ]
                cmap = settings.COLOURMAP_DICT["hydrological"]
            elif index in ["R10mm"]:
                bounds = [-20, -8, -6, -4, -2, 0, 2, 4, 6, 8, 20]
                cmap = settings.COLOURMAP_DICT["hydrological"]
            elif index in ["R20mm"]:
                bounds = [-20, -4, -3, -2, -1, 0, 1, 2, 3, 4, 20]
                cmap = settings.COLOURMAP_DICT["hydrological"]
            elif index in ["R95p"]:
                bounds = [
                    -1000, -100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100,
                    1000
                ]
                cmap = settings.COLOURMAP_DICT["hydrological"]
            elif index in ["PRCPTOT"]:
                bounds = [
                    -1000, -150, -80, -60, -40, -20, 0, 20, 40, 60, 80, 150,
                    1000
                ]
                cmap = settings.COLOURMAP_DICT["hydrological"]

            utils.plot_smooth_map_iris(
                settings.IMAGELOC +
                "PEX_{}_{}_anoms_ghcndex".format(index, settings.YEAR),
                anoms[loc[0]],
                cmap,
                bounds,
                "{} ({})".format(index, ETCCDI_UNITS[index]),
                title="GHCNDEX {} - {}".format(index, ETCCDI_LABELS[index]))
            if index == "Rx1day":
                utils.plot_smooth_map_iris(
                    settings.IMAGELOC + "p2.1_PEX_{}_{}_anoms_ghcndex".format(
                        index, settings.YEAR),
                    anoms[loc[0]],
                    cmap,
                    bounds,
                    "{} ({})".format(index, ETCCDI_UNITS[index]),
                    figtext="(k) Maximum 1 Day Precipitation Amount")

            rank_cube = get_ranks(anoms)

            plot_rank_map(
                settings.IMAGELOC +
                "PEX_{}_{}_rank_ghcndex".format(index, settings.YEAR),
                rank_cube[loc[0]],
                cmap,
                rank_bounds,
                "Rank",
                title="{} - {}".format(index, ETCCDI_UNITS[index]))
            #*************
            # plot season maps (2x2)

            if index in ["Rx1day", "Rx5day"]:

                for sc, cube in enumerate([total_cube, anoms]):

                    season_list = []
                    for season in SEASONS:

                        # extract each month
                        month_data = []
                        months = SEASON_DICT[season]
                        for month in months:

                            selected_cube, = np.where(names == month)
                            cube = cube_list[selected_cube[0]]

                            if month == "Dec":
                                # need to extract from previous year - cheat by rolling data around
                                cube.data = np.roll(cube.data, 1, axis=0)
                                cube.data.mask[
                                    0, :, :] = True  # and mask out the previous years'

                            month_data += [cube.data]

                        # finished getting all months, make a dummy cube to populate
                        month_data = np.ma.array(month_data)
                        season_cube = copy.deepcopy(cube)

                        # take appropriate seasonal value
                        season_cube.data = np.ma.max(month_data, axis=0)

                        # mask if fewer that 2 months present
                        nmonths_locs = np.ma.count(month_data, axis=0)
                        season_cube.data = np.ma.masked_where(
                            nmonths_locs < 2, season_cube.data)

                        # make anomalies
                        if sc == 1:
                            season_cube = ApplyClimatology(season_cube)

                        # fix for plotting
                        season_cube.coord('latitude').guess_bounds()
                        season_cube.coord('longitude').guess_bounds()

                        # select the year to plot
                        years = GetYears(cube)
                        loc, = np.where(years == SELECTED_YEAR)

                        # add to list
                        season_list += [season_cube[loc[0]]]

                    # sort the bounds and colourbars
                    if sc == 0:
                        if index in ["Rx1day", "Rx5day"]:
                            bounds = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
                            cmap = settings.COLOURMAP_DICT["precip_sequential"]

                        # pass to plotting routine
                        utils.plot_smooth_map_iris_multipanel(
                            settings.IMAGELOC +
                            "PEX_{}_{}_seasons_ghcndex".format(
                                index, settings.YEAR),
                            season_list,
                            cmap,
                            bounds,
                            "{} ({})".format(index, ETCCDI_UNITS[index]),
                            shape=(2, 2),
                            title=SEASONS,
                            figtext=["(a)", "(b)", "(c)", "(d)"],
                            figtitle="{} - {}".format(index,
                                                      ETCCDI_LABELS[index]))
                    elif sc == 1:
                        cmap = settings.COLOURMAP_DICT["hydrological"]
                        if index in ["Rx1day"]:
                            bounds = [
                                -100, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10,
                                100
                            ]
                        elif index in ["Rx5day"]:
                            bounds = [
                                -100, -20, -16, -12, -8, -4, 0, 4, 8, 12, 16,
                                20, 100
                            ]

                        # pass to plotting routine
                        utils.plot_smooth_map_iris_multipanel(
                            settings.IMAGELOC +
                            "PEX_{}_{}_anoms_seasons_ghcndex".format(
                                index, settings.YEAR),
                            season_list,
                            cmap,
                            bounds,
                            "{} ({})".format(index, ETCCDI_UNITS[index]),
                            shape=(2, 2),
                            title=SEASONS,
                            figtext=["(a)", "(b)", "(c)", "(d)"],
                            figtitle="{} - {}".format(index,
                                                      ETCCDI_LABELS[index]))

    #*************************
    # DWD indices
    if True:
        for index in DWD_INDICES:
            print(index)
            if not os.path.exists(
                    DATALOC +
                    "First_Guess_Daily_{}_{}.nc".format(settings.YEAR, index)):
                print("File {} missing".format(
                    "First_Guess_Daily_{}_{}.nc".format(settings.YEAR, index)))
                continue
            cube_list = iris.load(
                DATALOC +
                "First_Guess_Daily_{}_{}.nc".format(settings.YEAR, index))

            if len(cube_list) == 1:
                cube = cube_list[0]
            else:
                # these have two fields
                for cube in cube_list:
                    if cube.units == "mm per 5 day" and index == "RX5":
                        break
                    elif cube.var_name == "consecutive_wet_days_index_per_time_period" and index == "CWD":
                        break
                    elif cube.var_name == "consecutive_dry_days_index_per_time_period" and index == "CDD":
                        break
                    else:
                        print(
                            "Check cube for {} for extra fields".format(index))

            cube = cube[0]  # take only single slice
            cube.coord('latitude').guess_bounds()
            cube.coord('longitude').guess_bounds()

            if index in ["CDD"]:
                bounds = [0, 20, 40, 60, 80, 100, 120, 140, 160, 180]
                cmap = settings.COLOURMAP_DICT["precip_sequential_r"]
            elif index in ["CWD"]:
                bounds = [0, 20, 40, 60, 80, 100, 120, 140, 160, 180]
                bounds = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
                cmap = settings.COLOURMAP_DICT["precip_sequential"]
            elif index in ["DD"]:
                bounds = [0, 40, 80, 120, 160, 200, 240, 280, 320, 360]
                cmap = settings.COLOURMAP_DICT["precip_sequential_r"]
            elif index in ["PD"]:
                bounds = [0, 40, 80, 120, 160, 200, 240, 280, 320, 360]
                cmap = settings.COLOURMAP_DICT["precip_sequential"]
            elif index in ["RX1", "PD10"]:
                bounds = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
                cmap = settings.COLOURMAP_DICT["precip_sequential"]
            elif index in ["RX5"]:
                bounds = [0, 50, 100, 150, 200, 250, 300, 350, 400, 450]
                bounds = [0, 20, 40, 60, 80, 100, 120, 140, 160, 180]
                cmap = settings.COLOURMAP_DICT["precip_sequential"]
            elif index in ["R10", "R20", "R95P", "SDII", "PD20"]:
                bounds = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45]
                cmap = settings.COLOURMAP_DICT["precip_sequential"]

            utils.plot_smooth_map_iris(
                settings.IMAGELOC +
                "PEX_{}_{}_dwd".format(index, settings.YEAR),
                cube,
                cmap,
                bounds,
                "{} ({})".format(index, DWD_UNITS[index]),
                title="{} - {}".format(index, DWD_LABELS[index]))

    #*************************
    # DWD differences indices
    if True:
        for index in DWD_INDICES:
            print(index)
            if not os.path.exists(
                    DATALOC +
                    "Diff_{}-Mean_{}.nc".format(index, settings.YEAR)):
                print("File {} missing".format("Diff_{}-Mean_{}.nc".format(
                    index, settings.YEAR)))
                continue
            cube_list = iris.load(
                DATALOC + "Diff_{}-Mean_{}.nc".format(index, settings.YEAR))

            if len(cube_list) == 1:
                cube = cube_list[0]
            else:
                # these have two fields
                for cube in cube_list:
                    if cube.units == "mm per 5 day" and index == "RX5":
                        break

            cube = cube[0]  # take only single slice
            cube.coord('latitude').guess_bounds()
            cube.coord('longitude').guess_bounds()

            if index in ["RX1"]:
                bounds = [-100, -50, -25, -10, -5, 0, 5, 10, 25, 50, 100]
                cmap = settings.COLOURMAP_DICT["hydrological"]
            elif index in ["RX5"]:
                bounds = [-50, -30, -20, -10, -5, 0, 5, 10, 20, 30, 50]
                bounds = [-100, -50, -25, -10, -5, 0, 5, 10, 25, 50, 100]
                cmap = settings.COLOURMAP_DICT["hydrological"]
            elif index in ["PD10", "PD20", "R95P"]:
                bounds = [-50, -30, -20, -10, -5, 0, 5, 10, 20, 30, 50]
                cmap = settings.COLOURMAP_DICT["hydrological"]

            utils.plot_smooth_map_iris(
                settings.IMAGELOC +
                "PEX_{}_{}_diff_dwd".format(index, settings.YEAR),
                cube,
                cmap,
                bounds,
                "Anomalies from 1982-2016 {} ({})".format(
                    index, DWD_UNITS[index]),
                title="{} - {}".format(index, DWD_LABELS[index]))
            if index == "PD10":
                utils.plot_smooth_map_iris(
                    settings.IMAGELOC +
                    "p2.1_PEX_{}_{}_diff_dwd".format("R10mm", settings.YEAR),
                    cube,
                    cmap,
                    bounds,
                    "Anomalies from 1982-2016 {} ({})".format(
                        "R10mm", ETCCDI_UNITS["R10mm"]),
                    figtext="(l) {} anomalies".format("R10mm"))
            else:
                utils.plot_smooth_map_iris(
                    settings.IMAGELOC +
                    "p2.1_PEX_{}_{}_diff_dwd".format(index, settings.YEAR),
                    cube,
                    cmap,
                    bounds,
                    "Anomalies from 1982-2016 {} ({})".format(
                        index, DWD_UNITS[index]),
                    figtext="(l) {} anomalies".format(index))

    #*************************
    # MERRA map
    if True:
        index = "R10mm"
        cube = iris.load(DATALOC + "MERRA2_ann_2019_r10mm_gl_anom.nc")[0]

        bounds = [-50, -30, -20, -10, -5, 0, 5, 10, 20, 30, 50]
        cmap = settings.COLOURMAP_DICT["hydrological"]

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "PEX_R10mm_{}_merra2".format(settings.YEAR),
            cube[0],
            cmap,
            bounds,
            "{} ({})".format(index, ETCCDI_UNITS[index]),
            title="MERRA-2 {} - {}".format(index, ETCCDI_LABELS[index]))

    #*************************
    # ERA5 map
    if False:
        index = "Rx1day"
        cube = read_era5("prmax_{}.txt".format(settings.YEAR))

        bounds = [0, 2, 5, 10, 20, 40, 80, 160, 300, 450]
        cmap = settings.COLOURMAP_DICT["precip_sequential"]

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "PEX_Rx1day_{}_era5".format(settings.YEAR),
            cube,
            cmap,
            bounds,
            "{} ({})".format(index, ETCCDI_UNITS[index]),
            title="ERA5 {} - {}".format(index, ETCCDI_LABELS[index]))

    #*************************
    # ERA5 map
    if True:
        index = "Rx1day"
        cube = read_era5("prmax1d_anomaly_for_{}_wrt_1981-2010.txt".format(
            settings.YEAR))

        bounds = [-400, -100, -75, -50, -25, 0, 25, 50, 75, 100, 400]
        bounds = [-400, -100, -50, -20, -10, 0, 10, 20, 50, 100, 400]
        bounds = [-100, -40, -30, -20, -10, -5, 0, 5, 10, 20, 30, 40, 100]
        cmap = settings.COLOURMAP_DICT["hydrological"]

        utils.plot_smooth_map_iris(
            settings.IMAGELOC +
            "PEX_Rx1day_{}_anoms_era5".format(settings.YEAR),
            cube,
            cmap,
            bounds,
            "{} ({})".format(index, ETCCDI_UNITS[index]),
            title="ERA5 {} - {}".format(index, ETCCDI_LABELS[index]))
    #    utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_PEX_Rx1day_{}_anoms_era5".format(settings.YEAR), cube, cmap, bounds, "{} ({})".format(index, ETCCDI_UNITS[index]), figtext="(i) Rx1day anomalies")

    # cube = read_era5("prmax_for_{}_as_a_percentage_of_1981-2010_mean.txt".format(settings.YEAR))

    # bounds = [0, 10, 25, 50, 75, 100, 150, 200, 250, 300, 1000]
    # cmap = settings.COLOURMAP_DICT["hydrological"]

    # utils.plot_smooth_map_iris(settings.IMAGELOC + "PEX_Rx1day_{}_anoms_percent_era5".format(settings.YEAR), cube, cmap, bounds, "Anomalies from 1981-2010 (%)", title="ERA5 - Rx1day %")
    # utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_PEX_Rx1day_{}_anoms_percent_era5".format(settings.YEAR), cube, cmap, bounds, "Anomalies from 1981-2010 (%)", figtext="(m) Rx1day anomalies")

    #*************************
    # DWD percentile
    if True:

        #        dwd_cube = read_dwd_percentile(DATALOC + "GPCC_perzentile_{}.xyzras".format(settings.YEAR))

        cube_list = iris.load(DATALOC + "Quantile_12month_{}01-{}12.nc".format(
            settings.YEAR, settings.YEAR))
        dwd_cube = cube_list[0][0]

        bounds = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
        cmap = settings.COLOURMAP_DICT["hydrological"]
        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "PEX_{}_{}_dwd".format("R90", settings.YEAR),
            dwd_cube,
            cmap,
            bounds,
            "{} ({})".format("percentile", "%"),
            title="Percentile of the annual precipitation total")
        utils.plot_smooth_map_iris(
            settings.IMAGELOC +
            "p2.1_PEX_{}_{}_dwd".format("R90", settings.YEAR),
            dwd_cube,
            cmap,
            bounds,
            "{} ({})".format("percentile", "%"),
            figtext="(l) Percentile of the Annual Precipitation Total")

    #*************************
    # DWD drought
    if True:

        #        dwd_cube = read_dwd_percentile(DATALOC + "GPCC_perzentile_{}.xyzras".format(settings.YEAR))

        cube_list = iris.load(DATALOC + "GPCC_DI_201912_12.nc")
        dwd_cube = cube_list[0][0]

        bounds = [-10, -5, -3, -2, -1, 0, 1, 2, 3, 5, 10]
        cmap = settings.COLOURMAP_DICT["hydrological"]
        utils.plot_smooth_map_iris(settings.IMAGELOC +
                                   "PEX_{}_{}_dwd".format("DI", settings.YEAR),
                                   dwd_cube,
                                   cmap,
                                   bounds,
                                   "{} ({})".format("DI", "-"),
                                   title="12 month Drought Index")

    #*************************
    # GHCND totals and ratios
    if False:
        import cartopy.feature as cfeature

        NAMES = {"japan": "Japan", "neaus": "Australia", "hawaii": "Hawaii"}
        EXTENTS = {
            "japan": (132, 33, [126, 139, 30, 36]),
            "neaus": (145, -17, [139, 151, -26, -8]),
            "hawaii": (-158, 20, [-161, -154, 18.5, 22.5])
        }

        land_10m = cfeature.NaturalEarthFeature(
            'physical',
            'land',
            '10m',
            edgecolor='face',
            facecolor=cfeature.COLORS['land'])
        land_50m = cfeature.NaturalEarthFeature(
            'physical',
            'land',
            '50m',
            edgecolor='face',
            facecolor=cfeature.COLORS['land'])

        for index in ["Rx5day", "Rx1day"]:
            for state in ["03-neaus", "07-japan", "08-hawaii"]:

                print("{} - {}".format(state, index))
                lats, lons, value_mm, prev_value_mm = read_ghcnd(
                    "{}/{}-{}-non0-sorted-{}.txt".format(
                        DATALOC, index, settings.YEAR, state))

                ratio = value_mm / prev_value_mm

                # set up figure
                if "neaus" in state:
                    fig = plt.figure(figsize=(8, 5))
                else:
                    fig = plt.figure(figsize=(8, 3.5))

                if index == "Rx5day":
                    bounds = [0, 100, 200, 300, 400, 500, 600, 700, 800, 900]
                elif index == "Rx1day":
                    bounds = [0, 50, 100, 150, 200, 250, 300, 350, 400, 450]
                cmap = settings.COLOURMAP_DICT["precip_sequential"]
                norm = mpl.cm.colors.BoundaryNorm(bounds, cmap.N)

                #            ratio_cmap = plt.cm.YlOrRd
                #            ratio_bounds = [1, 1.05, 1.1, 1.15, 1.2, 1.3, 1.5, 1.75, 2.0 ]
                #            ratio_cmap = settings.COLOURMAP_DICT["hydrological"]
                #            ratio_bounds = [0.01, 0.5, 0.75, 0.9, 0.95, 1.0, 1.05, 1.1, 1.25, 2.0, 10.0]
                ratio_cmap = plt.cm.Blues
                ratio_bounds = [
                    0.01, 0.5, 0.7, 0.9, 1.0, 1.1, 1.3, 1.5, 2.0, 10.0
                ]
                ratio_norm = mpl.cm.colors.BoundaryNorm(
                    ratio_bounds, ratio_cmap.N)

                plt.clf()

                # set up axes
                ax0 = plt.axes([0.01, 0.12, 0.45, 0.85],
                               projection=cartopy.crs.Stereographic(
                                   central_longitude=EXTENTS[state[3:]][0],
                                   central_latitude=EXTENTS[state[3:]][1]))
                ax1 = plt.axes([0.51, 0.12, 0.45, 0.85],
                               projection=cartopy.crs.Stereographic(
                                   central_longitude=EXTENTS[state[3:]][0],
                                   central_latitude=EXTENTS[state[3:]][1]))

                for ax in [ax0, ax1]:
                    ax.set_extent(EXTENTS[state[3:]][2],
                                  cartopy.crs.PlateCarree())

                    states_provinces = cfeature.NaturalEarthFeature(
                        category='cultural',
                        name='admin_1_states_provinces_lines',
                        scale='50m',
                        facecolor='none')
                    ax.add_feature(states_provinces, edgecolor='gray')
                    ax.coastlines(resolution="10m", linewidth=0.5)
                    ax.add_feature(land_50m,
                                   zorder=0,
                                   facecolor="0.9",
                                   edgecolor="k")

                    # add other features
                    ax.gridlines()  #draw_labels=True)
                    ax.add_feature(cartopy.feature.BORDERS,
                                   zorder=0,
                                   facecolor="0.9",
                                   edgecolor="k")

                #  plot
                for ax, data, cm, bnds, nrm, label in zip(
                    [ax0, ax1], [value_mm, ratio], [cmap, ratio_cmap],
                    [bounds, ratio_bounds], [norm, ratio_norm],
                    ["{} (mm)".format(index), "Ratio to previous record"]):

                    scatter = ax.scatter(lons, lats, c=data, cmap=cm, norm=nrm, s=50, \
                                             transform=cartopy.crs.Geodetic(), edgecolor='0.5', linewidth=0.5)

                    # thicken border of colorbar and the dividers
                    # http://stackoverflow.com/questions/14477696/customizing-colorbar-border-color-on-matplotlib
                    if "Ratio" in label:
                        cb = fig.colorbar(scatter, ax=ax, orientation='horizontal', pad=0.05, fraction=0.05, \
                                        aspect=30, ticks=bnds[1:-1], label=label, drawedges=True)
                        cb.set_ticklabels(
                            ["{:g}".format(b) for b in bnds[1:-1]])
                    else:
                        cb = fig.colorbar(scatter, ax=ax, orientation='horizontal', pad=0.05, fraction=0.05, \
                                        aspect=30, ticks=bnds[1:-1], label=label, drawedges=True)
                        cb.set_ticklabels(["{:g}".format(b) for b in bnds])

                    cb.outline.set_linewidth(2)
                    cb.dividers.set_color('k')
                    cb.dividers.set_linewidth(2)
                    cb.ax.tick_params(axis='x',
                                      labelsize=settings.FONTSIZE * 0.6,
                                      direction='in')

                if index == "Rx5day" and state[3:] == "hawaii":
                    ax0.text(0.05,
                             1.05,
                             "(a)",
                             transform=ax0.transAxes,
                             fontsize=settings.FONTSIZE * 0.8)
                    ax1.text(0.05,
                             1.05,
                             "(b)",
                             transform=ax1.transAxes,
                             fontsize=settings.FONTSIZE * 0.8)
                elif index == "Rx1day" and state[3:] == "hawaii":
                    ax0.text(0.05,
                             1.05,
                             "(c)",
                             transform=ax0.transAxes,
                             fontsize=settings.FONTSIZE * 0.8)
                    ax1.text(0.05,
                             1.05,
                             "(d)",
                             transform=ax1.transAxes,
                             fontsize=settings.FONTSIZE * 0.8)

                plt.savefig(
                    settings.IMAGELOC +
                    "PEX_{}_{}-{}".format(index, NAMES[state[3:]], state[:2]) +
                    settings.OUTFMT)
                plt.close()

    return  # run_all_plots
Пример #14
0
def run_all_plots():


    # #***********************
    # # Three panel timeseries - UK, DWD, Windermere
    


    # chlorophyll = read_lake_csv(os.path.join(data_loc, "timeseries", "Windermere.csv"))
    # betula_out = read_dwd_betula(os.path.join(data_loc, "timeseries", "dwd-data_per180112_Betula_pendula_leaf_out.csv"))
    # quercus_out, quercus_fall = read_dwd_quercus(os.path.join(data_loc, "timeseries", "dwd-data_per-180112_Quercus robur leave unf.csv"))
    # betula_fall, fagus_out, fagus_fall = read_dwd_fagus(os.path.join(data_loc, "timeseries", "dwd-data_per180112_Fagus sylvatica and Betula pendula leaf data.csv"))

    # alder, chestnut, oak, beech = read_uk_csv(os.path.join(data_loc, "timeseries", "details_for_climate_report.csv"))
    # long_oak = read_uk_oak_csv(os.path.join(data_loc, "timeseries", "NatureCalendar_pedunculate_oak_first_leaf_1753_1999.csv"))

    # fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(8, 7), sharex=True)

    # # DWD data - budburst
    # utils.plot_ts_panel(ax1, [betula_out, fagus_out, quercus_out], "-", "phenological", loc="")

    # lines, labels = ax1.get_legend_handles_labels()
    # newlabels = []
    # for ll in labels:
    #     newlabels += [r'${}$'.format(ll)]
    # ax1.legend(lines, newlabels, loc="lower left", ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, labelspacing=0.1, columnspacing=0.5)
    # ax4 = plt.axes([0.84, 0.84, 0.15, 0.15])  
    # img = mpimg.imread(os.path.join(data_loc, 'DWD_oak_leaf.jpg'))
    # ax4.imshow(img)
    # ax4.set_xticks([])
    # ax4.set_yticks([])
    

    # # UK data - budburst
    # utils.plot_ts_panel(ax2, [alder, chestnut, beech, long_oak, oak], "-", "phenological", loc="")
    # ax2.plot(long_oak.times, long_oak.data, ls=None, marker="o", c=settings.COLOURS["phenological"][long_oak.name], markeredgecolor=settings.COLOURS["phenological"][long_oak.name])
    # lines, labels = ax2.get_legend_handles_labels()
    # newlabels = []
    # for ll in labels:
    #     newlabels += [r'${}$'.format(ll)]
    # ax2.legend(lines, newlabels, loc="lower left", ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, labelspacing=0.1, columnspacing=0.5)
    # ax5 = plt.axes([0.84, 0.54, 0.15, 0.15])  
    # img = mpimg.imread(os.path.join(data_loc, '61d1c433-b65c-47bc-b831-7e44ab74a895.jpg'))
    # ax5.imshow(img)
    # ax5.set_xticks([])
    # ax5.set_yticks([])

    # # Windermere
    # utils.plot_ts_panel(ax3, [chlorophyll], "-", "phenological", loc="lower left")
    # ax6 = plt.axes([0.84, 0.23, 0.15, 0.15])  
    # img = mpimg.imread(os.path.join(data_loc, 'Asterionella and aulacoseira 05 May 2017.jpg'))
    # ax6.imshow(img)
    # ax6.set_xticks([])
    # ax6.set_yticks([])

    # # prettify
    # ax1.set_ylim([70, 160])
    # ax2.set_ylim([70, 160])
    # ax3.set_ylim([70, 160])

    # ax2.set_ylabel("Day of year", fontsize=settings.FONTSIZE)

    # ax1.text(0.02, 0.88, "(a) Germany - tree leaf unfurling", transform=ax1.transAxes, fontsize=settings.FONTSIZE)
    # ax2.text(0.02, 0.88, "(b) UK - tree bud burst & leaf out", transform=ax2.transAxes, fontsize=settings.FONTSIZE)
    # ax3.text(0.02, 0.88, "(c) UK - Windermere - plankton", transform=ax3.transAxes, fontsize=settings.FONTSIZE)

    # for tick in ax3.xaxis.get_major_ticks():
    #     tick.label.set_fontsize(settings.FONTSIZE) 

    # minorLocator = MultipleLocator(100)
    # for ax in [ax1, ax2, ax3]:
    #     utils.thicken_panel_border(ax)
    #     ax.set_yticks(ax.get_yticks()[1:-1])
    #     ax.xaxis.set_minor_locator(minorLocator)
    #     for tick in ax.yaxis.get_major_ticks():
    #         tick.label.set_fontsize(settings.FONTSIZE) 

    # ax1.set_xlim([1950, 2020])

    # plt.setp([a.get_xticklabels() for a in [ax1, ax2]], visible=False)
    # fig.subplots_adjust(right=0.95, top=0.95, bottom=0.05, hspace=0.001)

    # plt.savefig(image_loc+"PHEN_tree_ts{}".format(settings.OUTFMT))
    # plt.close()


    # #***********************
    # # Barlett start/end timeseries - image inset
    # #   Hand-copied data from "Bartlett Gcc Transition Dates 2008-2017.xlsx"

    # # up, down, diff = read_bartlett_green(os.path.join(data_loc, "timeseries", "Bartlett_greenupdown.dat"))

    # # fig = plt.figure(figsize = (8, 9))
    # # plt.clf()

    # # # make axes by hand
    # # ax1 = plt.axes([0.15,0.3,0.8,0.65])
    # # ax2 = plt.axes([0.15,0.1,0.8,0.2], sharex = ax1)
    
    # # print "need inset axes for images"

    # # # plot data
    # # ax1.plot(up.times, up.data, c = "g", ls = "-", lw = 2, label = "Green up")
    # # ax1.plot(down.times, down.data, c = "brown", ls = "-", lw = 2, label = "Green down")
    # # ax1.fill_between(up.times, up.data, down.data, color = "0.75")

    # # ax2.plot(diff.times, diff.data, c = "c", ls = "-", lw = 2)

    # # ax1.legend(loc="upper right", ncol = 1, frameon = False, prop = {'size':settings.LEGEND_FONTSIZE}, labelspacing = 0.1, columnspacing = 0.5)

    # # # sort axes
    # # ax1.set_xlim([2008, 2018])
    # # ax2.set_ylim([140,180])
    # # ax1.text(0.02, 0.93, "(a) Bartlett seasons", transform = ax1.transAxes, fontsize = settings.FONTSIZE)
    # # ax2.text(0.02, 0.85, "(b) Difference", transform = ax2.transAxes, fontsize = settings.FONTSIZE)

    # # # prettify
    # # ax1.set_ylabel("Day of Year", fontsize = settings.FONTSIZE)
    # # ax2.set_ylabel("Days", fontsize = settings.FONTSIZE)
    # # minorLocator = MultipleLocator(100)
    # # for ax in [ax1, ax2]:
    # #     utils.thicken_panel_border(ax)
    # #     ax.set_yticks(ax.get_yticks()[1:-1])
    # #     ax.xaxis.set_minor_locator(minorLocator)
    # #     for tick in ax.yaxis.get_major_ticks():
    # #         tick.label.set_fontsize(settings.FONTSIZE) 
    # #     for tick in ax.xaxis.get_major_ticks():
    # #         tick.label.set_fontsize(settings.FONTSIZE) 

    # # plt.setp(ax1.get_xticklabels(), visible=False)

    # # plt.savefig(image_loc+"PHEN_bartlett_ts{}".format(settings.OUTFMT))
    # # plt.close()

    # #***********************
    # # Barlett start/end timeseries - image inset
    # #   Hand-copied data from "Bartlett Gcc Transition Dates 2008-2017.xlsx"
    # #   https://matplotlib.org/examples/pylab_examples/broken_axis.html

    # up, down, diff = read_bartlett_green(os.path.join(data_loc, "timeseries", "Bartlett_greenupdown.dat"))

    # fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(8, 9), sharex=True)

    # print("need inset axes for images")

    # # plot same on both
    # ax1.plot(up.times, up.data, c="g", ls="-", lw=2, label="Green up", marker="o")
    # ax1.plot(down.times, down.data, c="brown", ls="-", lw=2, label="Green down", marker="o")
    # ax1.fill_between(up.times, up.data, down.data, color="lightgreen")

    # ax2.plot(up.times, up.data, c="g", ls="-", lw=2, marker="o")
    # ax2.plot(down.times, down.data, c="brown", ls="-", lw=2, marker="o")
    # ax2.fill_between(up.times, up.data, down.data, color="lightgreen")

    # ax1.invert_yaxis()
    # ax2.invert_yaxis()

    # # hide the spines between ax and ax2
    # ax1.spines['bottom'].set_visible(False)
    # ax2.spines['top'].set_visible(False)
    # ax1.xaxis.tick_top()
    # ax1.tick_params(labeltop='off')  # don't put tick labels at the top
    # ax2.xaxis.tick_bottom()

    # # and the difference
    # ax3.plot(diff.times, diff.data, c="c", ls="-", lw=2, marker="o")

    # # plot the legend
    # ax1.legend(loc="upper right", ncol=1, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, labelspacing=0.1, columnspacing=0.5)
    
    # # prettify
    # ax1.set_xlim([2007, int(settings.YEAR)+1])
    # ax2.set_ylabel("Day of Year", fontsize=settings.FONTSIZE)
    # ax3.set_ylabel("Days", fontsize=settings.FONTSIZE)
    # ax1.text(0.02, 0.88, "(a) Bartlett seasons", transform=ax1.transAxes, fontsize=settings.FONTSIZE)
    # ax3.text(0.02, 0.85, "(b) Difference", transform=ax3.transAxes, fontsize=settings.FONTSIZE)

    # # zoom in
    # ax1.set_ylim([150, 100])
    # ax2.set_ylim([300, 250])
    # ax3.set_ylim([136, 179])

    # minorLocator = MultipleLocator(100)
    # for ax in [ax1, ax2, ax3]:
    #     utils.thicken_panel_border(ax)
    #     ax.set_yticks(ax.get_yticks()[1:-1])
    #     ax.xaxis.set_minor_locator(minorLocator)
    #     for tick in ax.yaxis.get_major_ticks():
    #         tick.label.set_fontsize(settings.FONTSIZE) 
    #     for tick in ax.xaxis.get_major_ticks():
    #         tick.label.set_fontsize(settings.FONTSIZE) 

    # plt.setp(ax1.get_xticklabels(), visible=False)
    # fig.subplots_adjust(right=0.95, top=0.95, hspace=0.001)


    # plt.savefig(image_loc+"PHEN_bartlett_ts_gap{}".format(settings.OUTFMT))
    # plt.close()

    # #***********************
    # # Bartlett GPP & Duke separate

    # fig = plt.figure(figsize=(8, 6.5))
    # plt.clf()
    # ax1 = plt.axes([0.12, 0.52, 0.78, 0.44])
    # ax2 = ax1.twinx()
    # ax3 = plt.axes([0.12, 0.08, 0.78, 0.44], sharex=ax1)
    
    # gpp, gcc = read_bartlett_gpp(os.path.join(data_loc, "timeseries", "Bartlett GPP Flux and Canopy Greenness.csv"))


    # bartlett, duke = read_bartlett_duke(os.path.join(data_loc, "timeseries", "Bartlett 2008-2017 and Duke 2017 Camera Greenness.csv"))

    # utils.plot_ts_panel(ax1, [gcc], "-", "phenological", loc="")
    # utils.plot_ts_panel(ax2, [gpp], "-", "phenological", loc="")
    # utils.plot_ts_panel(ax3, [bartlett, duke], "-", "phenological", loc="upper right", ncol=1)
    # ax3.axhline(0.36, c='0.5', ls='--')
    # ax3.axvline(185, c='0.5', ls=":")
    
    
    # # fix the legend
    # lines1, labels1 = ax1.get_legend_handles_labels()
    # lines2, labels2 = ax2.get_legend_handles_labels()
    # ax2.legend(lines1 + lines2, labels1 + labels2, loc="upper right", ncol=1, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, labelspacing=0.1, columnspacing=0.5)

    # # prettify
    # ax2.yaxis.set_label_position("right")
    # ax2.yaxis.set_ticks_position('right')

    # ax1.set_ylim([0.34, 0.48])
    # ax3.set_ylim([0.34, 0.48])
    # ax2.set_ylim([-2, 12])

    # ax1.set_ylabel("Canopy Greeness", fontsize=settings.FONTSIZE)
    # ax2.set_ylabel("Gross Primary Productivity", fontsize=settings.FONTSIZE)
    # ax3.set_ylabel("Canopy Greeness", fontsize=settings.FONTSIZE)

    # ax1.text(0.02, 0.88, "(c)", transform=ax1.transAxes, fontsize=settings.FONTSIZE)
    # ax3.text(0.02, 0.85, "(d)", transform=ax3.transAxes, fontsize=settings.FONTSIZE)

    # for tick in ax3.xaxis.get_major_ticks():
    #     tick.label.set_fontsize(settings.FONTSIZE) 

    # minorLocator = MultipleLocator(100)
    # for ax in [ax1, ax3]:
    #     utils.thicken_panel_border(ax)
    #     ax.set_yticks(ax.get_yticks()[1:-1])
    #     ax.xaxis.set_minor_locator(minorLocator)
    #     for tick in ax.yaxis.get_major_ticks():
    #         tick.label.set_fontsize(settings.FONTSIZE) 

    # utils.thicken_panel_border(ax2)
    # ax2.set_yticks(ax2.get_yticks()[1:-1])
    # for tick in ax2.yaxis.get_major_ticks():
    #     tick.label2.set_fontsize(settings.FONTSIZE)
    
    # plt.setp(ax1.get_xticklabels(), visible=False)
    # plt.setp(ax2.get_xticklabels(), visible=False)
    # fig.subplots_adjust(right=0.95, top=0.95, hspace=0.001)

    # ax4 = plt.axes([0.14, 0.65, 0.15, 0.15])  
    # img = mpimg.imread(os.path.join(data_loc, 'bbc7_2017_01_20_140005.jpg'))
    # ax4.imshow(img)
    # ax4.set_xticks([])
    # ax4.set_yticks([])
    # ax4.set_title("January")
    # ax5 = plt.axes([0.72, 0.65, 0.15, 0.15])  
    # img = mpimg.imread(os.path.join(data_loc, 'bbc7_2017_07_17_130005.jpg'))
    # ax5.imshow(img)
    # ax5.set_xticks([])
    # ax5.set_yticks([])
    # ax5.set_title("July")

    # ax6 = plt.axes([0.14, 0.25, 0.15, 0.15])  
    # img = mpimg.imread(os.path.join(data_loc, 'bbc7_2017_07_04_124505.jpg'))
    # ax6.imshow(img)
    # ax6.set_xticks([])
    # ax6.set_yticks([])
    # ax6.set_title("Bartlett")
    # ax7 = plt.axes([0.72, 0.25, 0.15, 0.15])  
    # img = mpimg.imread(os.path.join(data_loc, 'dukehw_2017_07_04_120110.jpg'))
    # ax7.imshow(img)
    # ax7.set_xticks([])
    # ax7.set_yticks([])
    # ax7.set_title("Duke")


    # plt.savefig(image_loc+"PHEN_Bartlett_GPP_Duke_separate{}".format(settings.OUTFMT))
    # plt.close()

    # #***********************
    # # Bartlett GPP & Duke combined

    # # fig = plt.figure(figsize = (8, 5))
    # # plt.clf()
    # # ax1 = plt.axes([0.12, 0.1, 0.78, 0.8])
    # # ax2 = ax1.twinx()
    
    # # gpp, gcc = read_bartlett_gpp(os.path.join(data_loc, "timeseries", "Bartlett GPP Flux and Canopy Greenness.csv"))

    # # bartlett, duke = read_bartlett_duke(os.path.join(data_loc, "timeseries", "Bartlett 2008-2017 and Duke 2017 Camera Greenness.csv"))

    # # utils.plot_ts_panel(ax1, [gcc, duke], "-", "phenological", loc = "")
    # # utils.plot_ts_panel(ax2, [gpp], "-", "phenological", loc = "")
    
    # # # fix the legend
    # # lines1, labels1 = ax1.get_legend_handles_labels()
    # # lines2, labels2 = ax2.get_legend_handles_labels()
    # # # have to remove duplicate label
    # # ax2.legend(lines1 + lines2, labels1 + labels2, loc="upper right", ncol = 1, frameon = False, prop = {'size':settings.LEGEND_FONTSIZE}, labelspacing = 0.1, columnspacing = 0.5)

    # # # prettify
    # # ax2.yaxis.set_label_position("right")

    # # ax1.set_ylim([0.34, 0.48])
    # # ax2.set_ylim([-2, 12])

    # # ax1.set_ylabel("Canopy Greeness", fontsize = settings.FONTSIZE)
    # # ax2.set_ylabel("Gross Primary Productivity", fontsize = settings.FONTSIZE)
 
    # # for tick in ax1.xaxis.get_major_ticks():
    # #     tick.label.set_fontsize(settings.FONTSIZE) 

    # # minorLocator = MultipleLocator(100)
    # # for ax in [ax1, ax3]:
    # #     utils.thicken_panel_border(ax)
    # #     ax.set_yticks(ax.get_yticks()[1:])
    # #     ax.xaxis.set_minor_locator(minorLocator)
    # #     for tick in ax.yaxis.get_major_ticks():
    # #         tick.label.set_fontsize(settings.FONTSIZE) 

    # # utils.thicken_panel_border(ax2)
    # # ax2.set_yticks(ax2.get_yticks()[1:-1])
    # # for tick in ax2.yaxis.get_major_ticks():
    # #     tick.label2.set_fontsize(settings.FONTSIZE)
    
    # # fig.subplots_adjust(right = 0.95, top = 0.95, hspace = 0.001)

    # # plt.savefig(image_loc+"PHEN_Bartlett_GPP_Duke_combined{}".format(settings.OUTFMT))
    # # plt.close()

    # #***********************
    # # UK Map
    # import cartopy.feature as cfeature
    # land_50m = cfeature.NaturalEarthFeature('physical', 'land', '50m',
    #                                         edgecolor='face',
    #                                         facecolor=cfeature.COLORS['land'])
 
    # species, days, lats, lons = read_uk_map_csv(os.path.join(data_loc, "timeseries", "UK_Leafout_4Trees.csv"))
    
    # cmap = plt.cm.YlGn
    # bounds = np.arange(80, 160, 10)
    # norm = mpl.cm.colors.BoundaryNorm(bounds, cmap.N)

    # fig = plt.figure(figsize=(8, 10.5))
    # plt.clf()
    # ax = plt.axes([0.05, 0.05, 0.9, 0.9], projection=cartopy.crs.LambertConformal(central_longitude=-7.5))

    # ax.gridlines() #draw_labels=True)
    # ax.add_feature(land_50m, zorder=0, facecolor="0.9", edgecolor="k")
    # ax.set_extent([-10, 4, 48, 60], cartopy.crs.PlateCarree())

    # scat = ax.scatter(lons, lats, c=days, transform=cartopy.crs.PlateCarree(), cmap=cmap, norm=norm, s=25, edgecolor='0.5', linewidth='0.5', zorder=10)

    # utils.thicken_panel_border(ax)

    # cb = plt.colorbar(scat, orientation='horizontal', ticks=bounds[1:-1], label="Day of year", drawedges=True, fraction=0.1, pad=0.05, aspect=15, shrink=0.8)

    # # prettify
    # cb.set_ticklabels(["{:g}".format(b) for b in bounds[1:-1]])
    # cb.outline.set_linewidth(2)
    # cb.dividers.set_color('k')
    # cb.dividers.set_linewidth(2)

    # plt.savefig(image_loc + "PHEN_UK_map{}".format(settings.OUTFMT))
    # plt.close()


    #***********************
    # MODIS

    cubelist = iris.load(os.path.join(data_loc, "MODIS.CMG.{}.SOS.EOS.Anomaly.nc".format(settings.YEAR)))

    for c, cube in enumerate(cubelist):
        if cube.name() == "EOS":
            eos_cube = cubelist[c]
        elif cube.name() == "SOS":
            sos_cube = cubelist[c]
        elif cube.name() == "MAX":
            max_cube = cubelist[c]
       
    # deal with NANS
#    eos_cube.data = np.ma.masked_where(eos_cube.data != eos_cube.data, eos_cube.data)
    sos_cube.data = np.ma.masked_where(sos_cube.data != sos_cube.data, sos_cube.data)
#    max_cube.data = np.ma.masked_where(max_cube.data != max_cube.data, max_cube.data)


            
    # set up a 1 x 2 set of axes (2018 only needs one panel)
    fig = plt.figure(figsize=(8, 8))
    plt.clf()

    # set up plot settings
    BOUNDS = [[-100, -20, -10, -5, -2, 0, 2, 5, 10, 20, 100]]#, [-100, -20, -10, -5, -2, 0, 2, 5, 10, 20, 100]]
    CMAPS = [settings.COLOURMAP_DICT["phenological_r"]]#, settings.COLOURMAP_DICT["phenological"]]

    CUBES = [sos_cube]# eos_cube]
    LABELS = ["(a) Start of Season (SOS)"]#, "(b) End of Season (EOS)"]

    # boundary circle
    theta = np.linspace(0, 2*np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpath.Path(verts * radius + center)

    # spin through axes
    for a in range(1):  

        ax = plt.subplot(1, 1, a+1, projection=cartopy.crs.NorthPolarStereo())

        plot_cube = CUBES[a]

        if settings.OUTFMT in [".eps", ".pdf"]:
            if plot_cube.coord("latitude").points.shape[0] > 90 or plot_cube.coord("longitude").points.shape[0] > 360:
                regrid_size = 1.0
                print("Regridding cube for {} output to {} degree resolution".format(settings.OUTFMT, regrid_size))
                print("Old Shape {}".format(plot_cube.data.shape))
                plot_cube = utils.regrid_cube(plot_cube, regrid_size, regrid_size)
                print("New Shape {}".format(plot_cube.data.shape))

        ax.gridlines() #draw_labels=True)
        ax.add_feature(cartopy.feature.LAND, zorder=0, facecolor="0.9", edgecolor="k")
        ax.coastlines()
        ax.set_boundary(circle, transform=ax.transAxes)
        ax.set_extent([-180, 180, 45, 90], cartopy.crs.PlateCarree())

        ext = ax.get_extent() # save the original extent

        cmap = CMAPS[a]
        norm = mpl.cm.colors.BoundaryNorm(BOUNDS[a], cmap.N)
        mesh = iris.plot.pcolormesh(plot_cube, cmap=cmap, norm=norm, axes=ax)

        ax.set_extent(ext, ax.projection) # fix the extent change from colormesh
        ax.text(-0.1, 1.0, LABELS[a], fontsize=settings.FONTSIZE * 0.8, transform=ax.transAxes)

        cb = plt.colorbar(mesh, orientation='horizontal', ticks=BOUNDS[a][1:-1], label="Anomaly (days)", drawedges=True, fraction=0.1, pad=0.05, aspect=15, shrink=0.8)
        # prettify
        cb.set_ticklabels(["{:g}".format(b) for b in BOUNDS[a][1:-1]])
        cb.outline.set_linewidth(2)
        cb.dividers.set_color('k')
        cb.dividers.set_linewidth(2)

        ax.set_extent([-180, 180, 45, 90], cartopy.crs.PlateCarree())

    fig.subplots_adjust(bottom=0.05, top=0.95, left=0.04, right=0.95, wspace=0.02)

    plt.title("")

    plt.savefig(image_loc + "PHEN_modis_polar{}".format(settings.OUTFMT))
    plt.close()

    del eos_cube
    del sos_cube
    del cubelist

    #***********************
    # MODIS LAI
    # max_cube.data = np.ma.masked_where(max_cube.data <= -9000, max_cube.data)
    # if settings.OUTFMT in [".eps", ".pdf"]:
    #     if max_cube.coord("latitude").points.shape[0] > 180 or max_cube.coord("longitude").points.shape[0] > 360:
    #         regrid_size = 1.0
    #         print("Regridding cube for {} output to {} degree resolution".format(settings.OUTFMT, regrid_size))
    #         print("Old Shape {}".format(max_cube.data.shape))
    #         max_cube = utils.regrid_cube(max_cube, regrid_size, regrid_size)
    #         print("New Shape {}".format(max_cube.data.shape))

    # fig = plt.figure(figsize=(8, 8))
    # plt.clf()
    # ax = plt.axes([0.05, 0.05, 0.9, 0.9], projection=cartopy.crs.NorthPolarStereo())

    # ax.gridlines() #draw_labels=True)
    # ax.add_feature(cartopy.feature.LAND, zorder=0, facecolor="0.9", edgecolor="k")
    # ax.coastlines()
    # ax.set_boundary(circle, transform=ax.transAxes)
    # ax.set_extent([-180, 180, 45, 90], cartopy.crs.PlateCarree())

    # ext = ax.get_extent() # save the original extent

    # cmap = settings.COLOURMAP_DICT["phenological_r"]
    # bounds = [-100, -5, -3, -2, -1, 0, 1, 2, 3, 5, 100]
    # norm = mpl.cm.colors.BoundaryNorm(bounds, cmap.N)
    # mesh = iris.plot.pcolormesh(max_cube, cmap=cmap, norm=norm, axes=ax)

    # ax.set_extent(ext, ax.projection) # fix the extent change from colormesh
    # ax.text(-0.1, 1.0, "Max Leaf Area Index", fontsize=settings.FONTSIZE * 0.8, transform=ax.transAxes)

    # cb = plt.colorbar(mesh, orientation='horizontal', ticks=bounds[1:-1], label="Anomaly (m"+r'$^2'+"/m"+r'$^2'+")", drawedges=True, fraction=0.1, pad=0.05, aspect=15, shrink=0.8)
    # # prettify
    # cb.set_ticklabels(["{:g}".format(b) for b in bounds[1:-1]])
    # cb.outline.set_linewidth(2)
    # cb.dividers.set_color('k')
    # cb.dividers.set_linewidth(2)

    # ax.set_extent([-180, 180, 45, 90], cartopy.crs.PlateCarree())

    # plt.savefig(image_loc + "PHEN_modis_lai{}".format(settings.OUTFMT))
    # plt.close()

    #***********************
    # MODIS timeseries - 2017

    # sos, eos, lai = read_modis_ts(os.path.join(data_loc, "MODIS.CMG.{}.SOS.EOS.MAX.AnomalyTS.csv".format(settings.YEAR)))


    # plt.clf()

    # fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 4), sharex=True)
    
    # # plot same on both
    # ax1.plot(sos.times, sos.data, c="g", ls="-", lw=2, label="Start of Season", marker="o")
    # ax1.plot(eos.times, eos.data, c="brown", ls="-", lw=2, label="End of Season", marker="o")
    # ax1.fill_between(eos.times, eos.data, sos.data, color="lightgreen")

    # ax2.plot(sos.times, sos.data, c="g", ls="-", lw=2, marker="o")
    # ax2.plot(eos.times, eos.data, c="brown", ls="-", lw=2, marker="o")
    # ax2.fill_between(eos.times, eos.data, sos.data, color="lightgreen")

    # # invert so green down is on the bottom
    # ax1.invert_yaxis()
    # ax2.invert_yaxis()

    # # hide the spines between ax and ax2
    # ax1.spines['bottom'].set_visible(False)
    # ax2.spines['top'].set_visible(False)
    # ax1.xaxis.tick_top()
    # ax1.tick_params(labeltop='off')  # don't put tick labels at the top
    # ax2.xaxis.tick_bottom()

    # # plot the legend
    # ax1.legend(loc="upper right", ncol=1, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, labelspacing=0.1, columnspacing=0.5)
    
    # # prettify
    # ax1.set_xlim([1999, 2018])
    # ax2.set_ylabel("Day of Year", fontsize=settings.FONTSIZE)

    # # zoom in
    # ax1.set_ylim([160, 110])
    # ax2.set_ylim([300, 250])

    # # set label
    # ax1.text(-0.1, 0.92, "(c)", transform=ax1.transAxes, fontsize=settings.FONTSIZE)

    # minorLocator = MultipleLocator(100)
    # for ax in [ax1, ax2]:
    #     utils.thicken_panel_border(ax)
    #     ax.set_yticks(ax.get_yticks()[1:-1])
    #     ax.xaxis.set_minor_locator(minorLocator)
    #     for tick in ax.yaxis.get_major_ticks():
    #         tick.label.set_fontsize(settings.FONTSIZE) 
    #     for tick in ax.xaxis.get_major_ticks():
    #         tick.label.set_fontsize(settings.FONTSIZE) 

    # plt.setp(ax1.get_xticklabels(), visible=False)
    # fig.subplots_adjust(right=0.95, top=0.95, hspace=0.001)

    # plt.savefig(image_loc+"PHEN_modis_ts{}".format(settings.OUTFMT))
    # plt.close()

    #***********************
    # MODIS timeseries - 2018
    
    sos_na, sos_ea, sprt_na, sprt_ea = read_modis_ts(os.path.join(data_loc, "MODIS.CMG.{}.SOS.EOS.SPRT.FALT.TS.csv".format(settings.YEAR)))

    dummy, sos_na = utils.calculate_climatology_and_anomalies_1d(sos_na, 2000, 2010)
    dummy, sos_ea = utils.calculate_climatology_and_anomalies_1d(sos_ea, 2000, 2010)

    fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6.5), sharex=True)

    # North America
    # use un-anomalised spring T to get legend without the data
    utils.plot_ts_panel(ax1, [sos_na, sprt_na], "-", "phenological", loc=LEGEND_LOC)   

    # Eurasia
    utils.plot_ts_panel(ax2, [sos_ea, sprt_ea], "-", "phenological", loc=LEGEND_LOC)

    # make twin axes for Spring T
    dummy, sprt_na = utils.calculate_climatology_and_anomalies_1d(sprt_na, 2000, 2010)
    dummy, sprt_ea = utils.calculate_climatology_and_anomalies_1d(sprt_ea, 2000, 2010)

    ax3 = ax1.twinx()
    utils.plot_ts_panel(ax3, [sprt_na], "-", "phenological", loc="")   

    ax4 = ax2.twinx()
    utils.plot_ts_panel(ax4, [sprt_ea], "-", "phenological", loc="")   

    # prettify
    ax1.set_ylim([-8, 8])
    ax2.set_ylim([-8, 8])
    ax3.set_ylim([2, -2])
    ax4.set_ylim([2, -2])

    # labels
    ax1.text(0.02, 0.88, "(a) North America", transform=ax1.transAxes, fontsize=settings.FONTSIZE)
    ax2.text(0.02, 0.88, "(b) Eurasia", transform=ax2.transAxes, fontsize=settings.FONTSIZE)

    ax1.text(0.47, 0.88, "2018 SOS Anomaly = 1.86 days", transform=ax1.transAxes, fontsize=settings.FONTSIZE*0.8)
    ax1.text(0.47, 0.78, "2018 Spring T anomaly = -0.75 "+r'$^{\circ}$'+"C", transform=ax1.transAxes, fontsize=settings.FONTSIZE*0.8)
    ax2.text(0.47, 0.88, "2018 SOS Anomaly = 2.01 days", transform=ax2.transAxes, fontsize=settings.FONTSIZE*0.8)
    ax2.text(0.47, 0.78, "2018 Spring T anomaly = 0.13 "+r'$^{\circ}$'+"C", transform=ax2.transAxes, fontsize=settings.FONTSIZE*0.8)

    fig.text(0.01, 0.5, "SOS Anomaly (days)", va='center', rotation='vertical', fontsize = settings.FONTSIZE)
    fig.text(0.95, 0.5, "Temperature Anomaly ("+r'$^{\circ}$'+"C)", va='center', rotation='vertical', fontsize = settings.FONTSIZE)

    # ticks and labels
    for tick in ax2.xaxis.get_major_ticks():
        tick.label.set_fontsize(settings.FONTSIZE) 

    minorLocator = MultipleLocator(1)
    for ax in [ax1, ax2]:
        utils.thicken_panel_border(ax)
        ax.set_yticks(ax.get_yticks()[1:-1])
        ax.xaxis.set_minor_locator(minorLocator)
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE) 

    for ax in [ax3, ax4]:
        ax.yaxis.tick_right()
        utils.thicken_panel_border(ax)
        ax.set_yticks(ax.get_yticks()[1:-1])
        ax.xaxis.set_minor_locator(minorLocator)
        for tick in ax.yaxis.get_major_ticks():
            tick.label2.set_fontsize(settings.FONTSIZE) 

    # final settings
    ax1.set_xlim([1999, 2020])

    plt.setp([a.get_xticklabels() for a in [ax1]], visible=False)
    fig.subplots_adjust(left=0.1, right=0.85, top=0.95, bottom=0.05, hspace=0.001)

    plt.savefig(image_loc+"PHEN_modis_ts{}".format(settings.OUTFMT))
    plt.close()



    return # run_all_plots
Пример #15
0
def run_all_plots():
    #************************************************************************
    # Timeseries figures

    at, at24 = read_csv(DATALOC + "mlo_trans_csv.txt")

    # get 6 and 24 month smoothed curves
    # at6 = make_smoothed_ts(at, 6)
    # at24 = make_smoothed_ts(at, 24)

    at_mean = np.mean(at.data[at.times < 1962])

    # fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6.5), sharex=True)
    fig = plt.figure(figsize=(8, 5))
    ax1 = plt.axes([0.15, 0.1, 0.8, 0.85])

    minor_tick_interval = 1
    minorLocator = MultipleLocator(minor_tick_interval)
    COLOURS = settings.COLOURS["radiation"]

    # full y - as scatter, do here
    ax1.plot(at.times,
             at.data,
             c=COLOURS[at.name],
             marker=".",
             label=at.name,
             ls="")
    ax1.axhline(at_mean, c='0.5', ls='--')
    ax1.xaxis.set_minor_locator(minorLocator)
    utils.thicken_panel_border(ax1)
    ax1.set_ylim([0.8, 0.95])
    ax1.plot(at24.times, at24.data, c="0.3", ls="-")

    # # zoomed y
    # ax2.plot(at.times, at.data, c = COLOURS[at.name], marker = ".", label = at.name, ls = "")

    # ax2.plot(at6.times, at6.data, c = "r", ls = "-")
    # ax2.plot(at24.times, at24.data, c = "b", ls = "-")

    # ax2.axhline(at_mean, c = '0.5', ls = '--')
    # ax2.xaxis.set_minor_locator(minorLocator)
    # utils.thicken_panel_border(ax2)
    # ax2.set_ylim([0.9,0.949])

    # prettify

    fig.text(0.03,
             0.5,
             "Apparent Transmission",
             va='center',
             rotation='vertical',
             fontsize=settings.FONTSIZE)

    ax1.text(1961, 0.9, "Agung", fontsize=settings.FONTSIZE)
    ax1.text(1970, 0.88, "El Chichon", fontsize=settings.FONTSIZE)
    ax1.text(1993, 0.88, "Pinatubo", fontsize=settings.FONTSIZE)

    ax1.text(2010, 0.9, "Nabro", fontsize=settings.FONTSIZE)
    ax1.plot([2012.5, 2012], [0.908, 0.92], "k-")

    ax1.fill_between([2002, 2012], [0.7, 0.7], [1.0, 1.0], color="0.7")
    ax1.fill_between([2017, 2020], [0.7, 0.7], [1.0, 1.0], color="0.7")

    plt.xlim([1954, int(settings.YEAR) + 2])
    for tick in ax1.yaxis.get_major_ticks():
        tick.label.set_fontsize(settings.FONTSIZE)
    for tick in ax1.xaxis.get_major_ticks():
        tick.label.set_fontsize(settings.FONTSIZE)

    # for tick in ax2.yaxis.get_major_ticks():
    #         tick.label.set_fontsize(settings.FONTSIZE)
    # for tick in ax2.xaxis.get_major_ticks():
    #     tick.label.set_fontsize(settings.FONTSIZE)

    fig.subplots_adjust(right=0.96, top=0.98, bottom=0.04, hspace=0.001)

    plt.savefig(settings.IMAGELOC + "AT_ts{}".format(settings.OUTFMT))
    plt.close()

    return  # run_all_plots
Пример #16
0
def run_all_plots():

    #************************************************************************
    # Timeseries - 2016
    if False:
        grasp, erai, era_presat, merra, jra55 = read_uaw_ts(DATALOC +
                                                            "20N-40N300.nc",
                                                            smooth=True)
        qbo = read_QBO(DATALOC + "qbo_1908_2015_REC_ERA40_ERAINT.txt")

        fig, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(5,
                                                      figsize=(8, 12),
                                                      sharex=True)

        # Observations
        utils.plot_ts_panel(ax1, [grasp],
                            "-",
                            "circulation",
                            loc=LEGEND_LOC,
                            ncol=2,
                            extra_labels=[" (0.02)"])

        # Reanalyses
        utils.plot_ts_panel(
            ax2, [erai, era_presat, jra55, merra],
            "-",
            "circulation",
            loc=LEGEND_LOC,
            ncol=2,
            extra_labels=[" (-0.20)", " (0.33)", " (-0.13)", " (-0.07)"])

        grasp, erai, era_presat, merra, jra55 = read_uaw_ts(DATALOC +
                                                            "10S-10N50.nc",
                                                            smooth=False)

        # Observations
        utils.plot_ts_panel(ax3, [qbo, grasp],
                            "-",
                            "circulation",
                            loc=LEGEND_LOC,
                            ncol=2,
                            extra_labels=["", " (-0.31)"])
        ax3.set_ylabel("Zonal Anomaly (m s" + r'$^{-1}$' + ")",
                       fontsize=settings.FONTSIZE)

        # Reanalyses
        utils.plot_ts_panel(
            ax4, [erai, era_presat, jra55, merra],
            "-",
            "circulation",
            loc=LEGEND_LOC,
            ncol=2,
            extra_labels=[" (-0.33)", " (-0.16)", " (-0.37)", " (0.30)"])

        fig.subplots_adjust(left=0.11, right=0.99, top=0.99, hspace=0.001)

        # turn on 4th axis ticks

        for tick in ax4.get_xticklabels():
            tick.set_visible(True)

        # delete the 5th axis and recreate - to break the sharex link
        fig.delaxes(ax5)
        ax5 = fig.add_subplot(515)
        pos = ax5.get_position()
        new_pos = [pos.x0, pos.y0 - 0.05, pos.width, pos.height]
        ax5.set_position(new_pos)

        # Obs & Reanalyses
        utils.plot_ts_panel(ax5, [grasp, erai, jra55, merra],
                            "-",
                            "circulation",
                            loc=LEGEND_LOC,
                            ncol=2)

        # sort formatting
        for ax in [ax4, ax5]:
            for tick in ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

        for ax in [ax1, ax2, ax3, ax4, ax5]:
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

        # x + y limit
        ax1.set_xlim([1930, 2017.9])
        ax1.set_ylim([-13, 6])
        ax1.yaxis.set_ticks([-10, -5, 0])
        ax2.set_ylim([-3.8, 3.8])
        ax2.yaxis.set_ticks([-2, 0, 2, 4])
        ax3.set_ylim([-34, 24])
        ax4.set_ylim([-34, 24])
        ax5.set_ylim([-34, 24])

        ax5.set_xlim([2000, 2017.9])

        # sort labelling
        ax1.text(0.02,
                 0.87,
                 "(a) Observations 20" + r'$^\circ$' + " - 40" + r'$^\circ$' +
                 "N 300hPa",
                 transform=ax1.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax2.text(0.02,
                 0.87,
                 "(b) Reanalyses 20" + r'$^\circ$' + " - 40" + r'$^\circ$' +
                 "N 300hPa",
                 transform=ax2.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax3.text(0.02,
                 0.87,
                 "(c) Observations & Reconstructions 10" + r'$^\circ$' +
                 "S - 10" + r'$^\circ$' + "N 50hPa",
                 transform=ax3.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax4.text(0.02,
                 0.87,
                 "(d) Reanalyses 10" + r'$^\circ$' + "S - 10" + r'$^\circ$' +
                 "N 50hPa",
                 transform=ax4.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax5.text(0.02,
                 0.87,
                 "(e) Observations & Reanalyses 10" + r'$^\circ$' + "S - 10" +
                 r'$^\circ$' + "N 50hPa",
                 transform=ax5.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)

        plt.savefig(settings.IMAGELOC + "UAW_ts{}".format(settings.OUTFMT))

    #************************************************************************
    # Timeseries - 2018
    if True:
        plt.figure(figsize=(8, 5))
        plt.clf()
        ax = plt.axes([0.12, 0.10, 0.87, 0.87])

        # Globe
        #    grasp, erai, cera, merra, jra55 = read_uaw_ts(DATALOC + "Globe850.nc", annual=True)
        era5, erai, merra, jra55 = read_uaw_ts(DATALOC + "Globe850_v2.nc",
                                               annual=True)
        utils.plot_ts_panel(ax, [merra, erai, era5, jra55], "-", "circulation", \
                            loc=LEGEND_LOC, ncol=2, extra_labels=[" (0.03)", " (0.07)", \
                                                                      " (0.03)", " (0.06)"])

        # sort formatting
        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        # x + y limit
        ax.set_xlim([1958, int(settings.YEAR) + 0.9])
        ax.set_ylim([-0.39, 1.0])
        ax.yaxis.set_ticks_position('left')
        ax.set_ylabel("Wind Anomaly (m s" + r'$^{-1}$' + ")",
                      fontsize=settings.LABEL_FONTSIZE)

        # # sort labelling
        ax.text(0.02,
                0.87,
                "Globe 850hPa",
                transform=ax.transAxes,
                fontsize=settings.LABEL_FONTSIZE)

        plt.savefig(settings.IMAGELOC +
                    "UAW_globe_ts{}".format(settings.OUTFMT))

    #*******
    # Tropics timeseries
    if False:
        fig = plt.figure(figsize=(8, 5))
        plt.clf()
        ax = plt.axes([0.10, 0.10, 0.87, 0.87])

        # 10N to 10S
        grasp, erai, cera, merra, jra55 = read_uaw_ts(DATALOC + "10S-10N50.nc")
        utils.plot_ts_panel(ax, [merra, erai, jra55, grasp], "-", "circulation",\
                                loc=LEGEND_LOC, ncol=2, extra_labels=[" (0.17)", " (-0.40)", \
                                                                          " (-0.51)", " (-0.30)"])

        # sort formatting
        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        # x + y limit
        ax.set_xlim([2000, int(settings.YEAR) + 2])
        ax.set_ylim([-28, 18])
        ax.yaxis.set_ticks_position('left')
        ax.set_ylabel("Wind Anomaly (m s" + r'$^{-1}$' + ")",
                      fontsize=settings.LABEL_FONTSIZE)

        # # sort labelling
        ax.text(0.02, 0.87, "10"+r'$^\circ$'+"S - 10"+r'$^\circ$'+"N 50hPa", \
                    transform=ax.transAxes, fontsize=settings.LABEL_FONTSIZE)

        plt.savefig(settings.IMAGELOC +
                    "UAW_tropics_ts{}".format(settings.OUTFMT))

    #************************************************************************
    # Global Map - ERA5 Anomaly figure
    if True:
        # Read in ERA5 anomalies

        # IRIS doesn't like the Conventions attribute
        ncfile = ncdf.Dataset(DATALOC + "ERA5_850_u.nc", 'r')

        var = ncfile.variables["u"][:]  # this is a masked array
        lons = ncfile.variables["longitude"][:]
        lats = ncfile.variables["latitude"][:]

        ncfile.close()

        # monthly data, so take mean
        print("not complete year used in 2019")
        mean = np.mean(var[7:], axis=0)

        cube = utils.make_iris_cube_2d(mean, lats, lons, "UAW_ANOM", "m/s")

        bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_UAW_{}_anoms_era5".format(settings.YEAR), \
                                       cube, settings.COLOURMAP_DICT["circulation"], bounds, \
                                       "Anomalies from 1981-2010 (m s"+r'$^{-1}$'+")", \
                                       figtext="(w) Upper Air (850-hPa) Eastward Winds (ASOND)")
        utils.plot_smooth_map_iris(settings.IMAGELOC + "UAW_{}_anoms_era5".format(settings.YEAR), \
                                       cube, settings.COLOURMAP_DICT["circulation"], bounds, \
                                       "Anomalies from 1981-2010 (m s"+r'$^{-1}$'+")")

    #************************************************************************
    # QBO plot - https://www.geo.fu-berlin.de/en/met/ag/strat/produkte/qbo/index.html
    if False:
        levels = np.array([70., 50., 40., 30., 20., 15., 10.])
        times = []
        dttimes = []
        data = np.zeros((levels.shape[0], 13))
        factor = 0.1
        j = 0

        with open(DATALOC + "qbo.dat", "r") as infile:

            for line in infile:
                line = line.split()

                if len(line) > 0:

                    # get current year
                    try:
                        if int(line[1][:2]) >= int(settings.YEAR[-2:]) and int(
                                line[1][:2]) <= int(settings.YEAR[-2:]) + 1:
                            month = int(line[1][-2:])
                            times += [month]
                            dttimes += [
                                dt.datetime(int(settings.YEAR), month, 1)
                            ]
                            data[:, j] = [float(i) * factor for i in line[2:]]
                            j += 1
                    except ValueError:
                        pass

        data = np.array(data)
        times = np.array(times)
        times[-1] += 12

        # And now plot
        cmap = settings.COLOURMAP_DICT["circulation"]
        bounds = [
            -100., -45., -30., -15., -10., -5., 0., 5., 10., 15., 30., 45., 100
        ]
        norm = mpl.cm.colors.BoundaryNorm(bounds, cmap.N)

        fig = plt.figure(figsize=(8, 8))
        plt.clf()
        ax = plt.axes([0.12, 0.07, 0.8, 0.9])

        times, levels = np.meshgrid(times, levels)

        con = plt.contourf(times,
                           levels,
                           data,
                           bounds,
                           cmap=cmap,
                           norm=norm,
                           vmax=bounds[-1],
                           vmin=bounds[1])

        plt.ylabel("Pressure (hPa)", fontsize=settings.FONTSIZE)
        plt.xlabel(settings.YEAR, fontsize=settings.FONTSIZE)
        plt.xticks(times[0], [dt.datetime.strftime(d, "%b") for d in dttimes],
                   fontsize=settings.FONTSIZE * 0.8)

        plt.xlim([1, 13])
        plt.ylim([70, 10])

        ax.set_yscale("log", subsy=[])
        plt.gca().yaxis.set_major_locator(
            matplotlib.ticker.MultipleLocator(10))
        plt.gca().yaxis.set_minor_locator(matplotlib.ticker.NullLocator())
        plt.gca().yaxis.set_major_formatter(
            matplotlib.ticker.ScalarFormatter())

        plt.yticks(np.arange(70, 0, -10),
                   ["{}".format(l) for l in np.arange(70, 0, -10)],
                   fontsize=settings.FONTSIZE)

        # colourbar and prettify
        cb = plt.colorbar(con, orientation='horizontal', pad=0.1, fraction=0.05, aspect=30, \
                              ticks=bounds[1:-1], label="zonal wind (m/s)", drawedges=True)

        cb.set_ticklabels(["{:g}".format(b) for b in bounds[1:-1]])
        cb.ax.tick_params(axis='x',
                          labelsize=settings.FONTSIZE * 0.6,
                          direction='in')

        cb.set_label(label="zonal wind (m/s)",
                     fontsize=settings.FONTSIZE * 0.6)
        #    cb.outline.set_color('k')
        cb.outline.set_linewidth(2)
        cb.dividers.set_color('k')
        cb.dividers.set_linewidth(2)

        utils.thicken_panel_border(ax)

        plt.savefig(settings.IMAGELOC +
                    "UAW_QBO_levels{}".format(settings.OUTFMT))

    #************************************************************************
    # https://www.geo.fu-berlin.de/met/ag/strat/produkte/qbo/singapore2019.dat
    if True:
        levels = []
        times = np.arange(1, 13, 1)
        data = []
        factor = 0.1
        j = 0

        with open(DATALOC + "singapore{}.dat".format(settings.YEAR),
                  "r") as infile:
            read = False
            for line in infile:
                line = line.split()
                if len(line) == 0:
                    continue

                if line[0] == "hPa":
                    read = True
                    continue
                elif read:

                    if len(line) > 0:

                        levels += [int(line[0])]
                        data += [[float(l) * 0.1 for l in line[1:]]]

                else:
                    continue

        # convert ot arrays and reorder
        levels = np.array(levels)
        levels = levels[::-1]
        data = np.array(data)
        data = data[::-1, :]

        # And now plot
        cmap = settings.COLOURMAP_DICT["circulation"]
        bounds = [
            -100., -45., -30., -15., -10., -5., 0., 5., 10., 15., 30., 45., 100
        ]
        norm = mpl.cm.colors.BoundaryNorm(bounds, cmap.N)

        fig = plt.figure(figsize=(8, 8))
        plt.clf()
        ax = plt.axes([0.12, 0.07, 0.85, 0.9])

        times, levels = np.meshgrid(times, levels)

        con = plt.contourf(times,
                           levels,
                           data,
                           bounds,
                           cmap=cmap,
                           norm=norm,
                           vmax=bounds[-1],
                           vmin=bounds[1])

        plt.ylabel("Pressure (hPa)", fontsize=settings.FONTSIZE)
        plt.xlabel(settings.YEAR, fontsize=settings.FONTSIZE)
        dttimes = [
            dt.datetime(int(settings.YEAR), m + 1, 1) for m in range(12)
        ]
        plt.xticks(times[0], [dt.datetime.strftime(d, "%b") for d in dttimes],
                   fontsize=settings.FONTSIZE)

        plt.xlim([1, 12])
        plt.ylim([100, 10])

        ax.set_yscale("log", subsy=[])
        plt.gca().yaxis.set_major_locator(
            matplotlib.ticker.MultipleLocator(10))
        plt.gca().yaxis.set_minor_locator(matplotlib.ticker.NullLocator())
        plt.gca().yaxis.set_major_formatter(
            matplotlib.ticker.ScalarFormatter())

        plt.yticks(np.arange(100, 0, -10),
                   ["{}".format(l) for l in np.arange(100, 0, -10)],
                   fontsize=settings.FONTSIZE)

        # colourbar and prettify
        cb = plt.colorbar(con, orientation='horizontal', pad=0.1, fraction=0.05, aspect=30, \
                              ticks=bounds[1:-1], drawedges=True)

        cb.set_ticklabels(["{:g}".format(b) for b in bounds[1:-1]])
        cb.set_label(label="zonal wind (m/s)", fontsize=settings.FONTSIZE)
        cb.ax.tick_params(axis='x',
                          labelsize=settings.FONTSIZE,
                          direction='in')

        cb.set_label(label="zonal wind (m/s)", fontsize=settings.FONTSIZE)
        #    cb.outline.set_color('k')
        cb.outline.set_linewidth(2)
        cb.dividers.set_color('k')
        cb.dividers.set_linewidth(2)

        utils.thicken_panel_border(ax)

        plt.savefig(settings.IMAGELOC + "UAW_levels{}".format(settings.OUTFMT))

    #************************************************************************
    # 200hPa winds in 1980 and 2018
    if False:
        cube_list = iris.load(DATALOC + "ws200_spread_197901_201801.nc")
        names = np.array([str(cube.var_name) for cube in cube_list])

        # hard coded labels
        mu = {"1980": "1.8", "2018": "1.0"}
        rms = {"1980": "2.0", "2018": "1.1"}
        label = {"1980": "(a)", "2018": "(b)"}
        bounds = [0, 0.5, 1, 1.5, 2, 2.5, 3.0, 100]
        for name in names:
            print(name)
            cube_index, = np.where(names == name)
            cube = cube_list[cube_index[0]]

            year = name.split("_")[-1][:4]

            utils.plot_smooth_map_iris(
                settings.IMAGELOC + "UAW_200hPa_Jan{}".format(year),
                cube,
                plt.cm.BuPu,
                bounds,
                "m/s",
                figtext="{} January {}, mean={}, RMS={}".format(
                    label[year], year, mu[year], rms[year]))

    #************************************************************************
    # Plots
    if False:
        label = {"1980": "(c)", "2018": "(d)"}
        for year in ["1980", "2018"]:

            cube_list = iris.load(DATALOC + "v200_zonal_{}01.nc".format(year))

            for cube in cube_list:
                if cube.var_name == "products":
                    names = cube
                elif cube.var_name == "v200_array":
                    data_array = cube

            latitudes = data_array.coord("latitude").points
            plt.figure()
            ax = plt.axes([0.13, 0.13, 0.85, 0.85])

            COLOURS = {
                "ERA5 ens. mean": "red",
                "ERA5 ensemble": "orange",
                "ERA5 HRES": "orange",
                "JRA55": "c",
                "MERRA-2": "m",
                "ERA-Interim": "orange"
            }

            for name, data in zip(names.data, data_array.data):

                str_name = "".join(str(name.compressed(), "latin-1").rstrip())
                # manually fix names
                if str_name == "ERAI":
                    str_name = "ERA-Interim"
                elif str_name == "ERA5 ens mean":
                    str_name = "ERA5 ens. mean"

                if str_name[:3] == "mem":
                    plt.plot(latitudes[1:], data[1:], c="orange")
                elif str_name == "ERA-Interim":
                    plt.plot(latitudes[1:],
                             data[1:],
                             c=COLOURS[str_name],
                             label=str_name,
                             lw=2,
                             ls="--")
                else:
                    plt.plot(latitudes[1:],
                             data[1:],
                             c=COLOURS[str_name],
                             label=str_name,
                             lw=2)

            plt.legend(loc="upper right", ncol=1, frameon=False)
            plt.xlabel("Latitude", fontsize=settings.FONTSIZE * 0.8)
            plt.ylabel("m/s", fontsize=settings.FONTSIZE * 0.8)
            plt.text(0.03,
                     0.92,
                     "{} January {}".format(label[year], year),
                     transform=ax.transAxes,
                     fontsize=settings.FONTSIZE * 0.8)

            plt.xlim([-90, 90])
            plt.xticks(np.arange(-90, 120, 30))
            plt.ylim([-1, 4])
            for tick in ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE * 0.8)
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE * 0.8)
            utils.thicken_panel_border(ax)

            plt.savefig(settings.IMAGELOC +
                        "UAW_200hPa_Jan{}_ts{}".format(year, settings.OUTFMT))

    return
Пример #17
0
def run_all_plots():

    #************************************************************************
    # Timeseries
    if True:

        cube_list = np.array(
            iris.load(DATALOC +
                      "ESA_CCI_SM_COMBINED_monthAnomaliesPerHemisphere.nc"))

        names = np.array([c.var_name for c in cube_list])

        north_obs = cube_list[names == "nObs_north"][0]
        south_obs = cube_list[names == "nObs_south"][0]
        glob_obs = cube_list[names == "nObs_global"][0]
        north = cube_list[names == "Anomalies_north"][0]
        south = cube_list[names == "Anomalies_south"][0]
        glob = cube_list[names == "Anomalies_global"][0]

        # as date in days-from - let Iris do the heavy lifting and do this one manually

        fig = plt.figure(figsize=(8, 6))
        ax1 = plt.axes([0.14, 0.2, 0.84, 0.79])

        iris.plot.plot(south, 'b', label="S. Hemisphere", lw=LW)
        iris.plot.plot(north, "0.5", label="N. Hemisphere", lw=LW)
        iris.plot.plot(glob, "k", label="Global", lw=LW)
        ax1.text(0.02,
                 0.9,
                 "ESA CCI SM",
                 transform=ax1.transAxes,
                 fontsize=settings.FONTSIZE)

        # number of observations
        ax2 = plt.axes([0.14, 0.07, 0.84, 0.13], sharex=ax1)

        south_obs.data = 100 * south_obs.data / 244243.
        north_obs.data = 100 * north_obs.data / 244243.
        glob_obs.data = 100 * glob_obs.data / 244243.

        iris.plot.plot(south_obs, 'b', lw=LW)
        iris.plot.plot(north_obs, "0.5", lw=LW)
        iris.plot.plot(glob_obs, "k", lw=LW)

        #*******************
        # prettify
        ax1.set_ylim([-0.021, 0.021])
        ax1.set_ylabel("Anomaly (m" + r'$^{3}$' + "m" + r'$^{-3}$' + ")",
                       fontsize=settings.FONTSIZE)
        ax1.axhline(0, c='0.5', ls='--')

        ax1.set_yticks([-0.02, -0.01, 0, 0.01, 0.02])

        ax2.set_ylim([0, 100])
        ax2.set_ylabel("% \n obs.", fontsize=settings.FONTSIZE)
        ax2.set_yticks([0, 25, 50, 75])

        for tick in ax2.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for ax in [ax1, ax2]:
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
            ax.yaxis.set_ticks_position('left')

        ax1.legend(loc=LEGEND_LOC,
                   ncol=1,
                   frameon=False,
                   prop={'size': settings.LEGEND_FONTSIZE},
                   labelspacing=0.1,
                   columnspacing=0.5)

        utils.thicken_panel_border(ax1)
        utils.thicken_panel_border(ax2)

        minorLocator = MultipleLocator(365.242199)  # in days since
        ax1.xaxis.set_minor_locator(minorLocator)

        lims = ax1.get_xlim()
        ax1.set_xlim([lims[0] - 100, lims[1] + 100])
        #    ax2.set_xticklabels("")

        plt.savefig(settings.IMAGELOC +
                    "SMS_ts_esa_cci{}".format(settings.OUTFMT))
        plt.close()

    #************************************************************************
    # Annual Map
    if True:
        cube_list = iris.load(DATALOC +
                              "ESA_CCI_SM_COMBINED_anomalyMaps_yearly.nc")

        cube = cube_list[0]
        cube.coord('latitude').guess_bounds()
        cube.coord('longitude').guess_bounds()

        bounds = [
            -100, -0.04, -0.03, -0.02, -0.01, 0, 0.01, 0.02, 0.03, 0.04, 100
        ]

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "SMS_{}_esa_cci".format(settings.YEAR),
            cube[-1], settings.COLOURMAP_DICT["hydrological"], bounds,
            "Anomalies from 1991-2010 (m" + r'$^{3}$' + "m" + r'$^{-3}$' + ")")

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "p2.1_SMS_{}_esa_cci".format(settings.YEAR),
            cube[-1],
            settings.COLOURMAP_DICT["hydrological"],
            bounds,
            "Anomalies from 1991-2010 (m" + r'$^{3}$' + "m" + r'$^{-3}$' + ")",
            figtext="(r) Soil Moisture")

    #************************************************************************
    # Seasonal Map
    if True:

        cube_list = iris.load(DATALOC +
                              "ESA_CCI_SM_COMBINED_anomalyMaps_monthly.nc")

        cube = cube_list[0]
        cube.coord('latitude').guess_bounds()
        cube.coord('longitude').guess_bounds()

        month_list = [cube[i] for i in range(-12, 0, 1)]

        utils.plot_smooth_map_iris_multipanel(
            settings.IMAGELOC + "SMS_{}_anoms_seasons".format(settings.YEAR),
            month_list,
            settings.COLOURMAP_DICT["hydrological"],
            bounds,
            "Anomaly (m" + r'$^{3}$' + "m" + r'$^{-3}$' + ")",
            shape=(6, 2),
            title=MONTHS,
            figtext=[
                "(a)", "(b)", "(c)", "(d)", "(e)", "(f)", "(g)", "(h)", "(i)",
                "(j)", "(k)", "(l)"
            ])

    #************************************************************************
    # Hovmuller
    if True:

        cube_list = iris.load(
            DATALOC + "ESA_CCI_SM_COMBINED_anomaly_hovmoeller_diagram.nc")

        for cube in cube_list:
            if cube.name() == "hovmoeller": break

        print("issues with masking in 2018 - remove and reset")

        data = cube.data[:]
        data.mask = np.zeros(data.shape)

        data = np.ma.masked_where(data == data.fill_value, data)
        cube.data = data

        # to here

        latitudes = cube.coord("latitude").points
        anoms = cube.data * 0.01  # added for offset in 2017 report

        bounds = [
            -100, -0.04, -0.03, -0.02, -0.01, 0, 0.01, 0.02, 0.03, 0.04, 100
        ]

        # extract the time data
        timeUnits = cube.coord("time").units
        dt_time = timeUnits.num2date(cube.coord("time").points)

        times = np.array([(date.year + (date.month - 1) / 12.)
                          for date in dt_time])

        utils.plot_hovmuller(settings.IMAGELOC + "SMS_hovmuller", times,
                             latitudes, anoms,
                             settings.COLOURMAP_DICT["hydrological"], bounds,
                             "Anomaly (m" + r'$^{3}$' + "m" + r'$^{-3}$' + ")")

    return  # run_all_plots
Пример #18
0
def plot_us_phenocam(ax, modis, pheno, sos=True):

    from matplotlib.ticker import MultipleLocator

    minor_tick_interval = 1
    minorLocator = MultipleLocator(minor_tick_interval)
    major_tick_interval = 5
    majorLocator = MultipleLocator(major_tick_interval)

    if sos:
        colors = ["#31a354", "#a1d99b", "#e5f5e0"]
    else:
        colors = ["#d95f0e", "#fec44f", "#fff7bc"]

    pheno_10, pheno_25, pheno_50, pheno_m, pheno_p = pheno

    ax.plot(modis.times, modis.data, c="k", ls="-", label=modis.name, lw=3)

    ax.plot(pheno_10.times,
            pheno_10.data,
            c=colors[0],
            ls="-",
            label=pheno_10.name,
            lw=3)
    ax.plot(pheno_25.times,
            pheno_25.data,
            c=colors[1],
            ls="-",
            label=pheno_25.name,
            lw=3)
    ax.errorbar(pheno_25.times,
                pheno_25.data,
                yerr=[pheno_m.data, pheno_p.data],
                c=colors[1],
                ls="-",
                label=None)
    ax.plot(pheno_50.times,
            pheno_50.data,
            c=colors[2],
            ls="-",
            label=pheno_50.name,
            lw=3)

    if sos:
        ax.legend(loc="upper left",
                  frameon=False,
                  ncol=1,
                  fontsize=settings.FONTSIZE * 0.8)
    else:
        ax.legend(loc="lower left",
                  frameon=False,
                  ncol=1,
                  fontsize=settings.FONTSIZE * 0.8)

    ax.xaxis.set_minor_locator(minorLocator)
    ax.xaxis.set_major_locator(majorLocator)
    # turn of RHS y ticks
    ax.yaxis.set_ticks_position('left')
    ax.set_xlim([2000, 2020])
    #    ax.set_ylabel("Day of Year", fontsize=settings.FONTSIZE)

    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(settings.FONTSIZE)
    for tick in ax.xaxis.get_major_ticks():
        tick.label.set_fontsize(settings.FONTSIZE)

    utils.thicken_panel_border(ax)

    return  # plot_us_phenocam
Пример #19
0
def run_all_plots():
    #************************************************************************
    # Timeseries

    data = read_binary_ts(DATALOC + "TimeSeries_faparanomaliesglobal_bams_v{}_C6_2020.bin".format(int(settings.YEAR)-1))

    fig = plt.figure(figsize=(8, 6))
    ax = plt.axes([0.13, 0.07, 0.8, 0.86])

    COLOURS = settings.COLOURS["land_surface"]

    for dataset in data:
        print(dataset.name)
        ls = "--"
        if dataset.name.split(" ")[-1] == "Smoothed":
            ls = "-"
        ax.plot(dataset.times, dataset.data, c=COLOURS[dataset.name], ls=ls, label=dataset.name, lw=LW)

    ax.axhline(0, c='0.5', ls='--')
    utils.thicken_panel_border(ax)

    ax.legend(loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, labelspacing=0.1, columnspacing=0.5)

    #*******************
    # prettify

    fig.text(0.01, 0.5, "Anomaly (FAPAR)", va='center', rotation='vertical', fontsize=settings.FONTSIZE)

    plt.xlim([1998-1, int(settings.YEAR)+2])
    plt.ylim([-0.022, None])

    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(settings.FONTSIZE)
    ax.xaxis.set_minor_locator(minorLocator)
    for tick in ax.xaxis.get_major_ticks():
        tick.label.set_fontsize(settings.FONTSIZE)

    plt.savefig(settings.IMAGELOC + "FPR_ts{}".format(settings.OUTFMT))
    plt.close()

    #************************************************************************
    # Hovmullers
    data = read_binary(DATALOC + "Hovmuller_Global_lat_fapar1998_2010_bams_trois_C6.eps_{}.bin".format(int(settings.YEAR)+1))

    # reshape - from Readme
    data = data.reshape(360, DURATION)

    data = np.ma.masked_where(data == 0., data)

    lats = np.arange(-90, 90, 0.5)

    bounds = [-20, -0.04, -0.03, -0.02, -0.01, 0, 0.01, 0.02, 0.03, 0.04, 20]
    utils.plot_hovmuller(settings.IMAGELOC + "FPR_hovmuller", times, lats, data, settings.COLOURMAP_DICT["phenological"], bounds, "Anomaly (FAPAR)")


    #************************************************************************
    # Anomalies
    data = read_binary(DATALOC + "DataXFigure1fapar1998_2010_bams_trois_C6_v2.eps_v2020.bin")
    data = data.reshape(360, 720)

    data = np.ma.masked_where(data == -100, data) # land/ocean mask
    data = np.ma.masked_where(data <= -9999., data) # missing data
    data = np.ma.masked_where(np.logical_and(data > -0.001, data < 0.001), data) # missing data

    lons = np.arange(-180, 180, 0.5)
    lats = np.arange(-90, 90, 0.5)

    cube = utils.make_iris_cube_2d(data, lats, lons, "FAPAR", "%")

    bounds = [-20, -0.04, -0.03, -0.02, -0.01, 0, 0.01, 0.02, 0.03, 0.04, 20]
    utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_FPR_{}".format(settings.YEAR), cube, settings.COLOURMAP_DICT["phenological"], bounds, "Anomalies from 1998-{} (FAPAR)".format(2010), figtext="(ae) Fraction of Absorbed Photosynthetically Active Radiation")
    utils.plot_smooth_map_iris(settings.IMAGELOC + "FPR_{}".format(settings.YEAR), cube, settings.COLOURMAP_DICT["phenological"], bounds, "Anomalies from 1998-{} (FAPAR)".format(2010))


    return # run_all_plots
Пример #20
0
def run_all_plots():

    #***********************
    # MODIS - centre
    if True:
        cubelist = iris.load(
            os.path.join(
                DATALOC,
                "MODIS.CMG.{}.SOS.EOS.Anomaly.nc".format(settings.YEAR)))
        names = np.array([c.name() for c in cubelist])
        # set up plot settings
        BOUNDS = [-100, -20, -10, -5, -2, 0, 2, 5, 10, 20, 100]
        LABELS = {
            "SOS": "(c) Start of Season (SOS)",
            "EOS": "(d) End of Season (EOS)"
        }

        for season in ["SOS", "EOS"]:

            c, = np.where(names == season)[0]

            cube = cubelist[c]

            # deal with NANS
            cube.data = np.ma.masked_where(cube.data != cube.data, cube.data)

            fig = plt.figure(figsize=(8, 11))
            plt.clf()

            # boundary circle
            theta = np.linspace(0, 2 * np.pi, 100)
            center, radius = [0.5, 0.5], 0.5
            verts = np.vstack([np.sin(theta), np.cos(theta)]).T
            circle = mpath.Path(verts * radius + center)

            # axes for polar plot
            ax = plt.axes([0.01, 0.02, 0.98, 0.65],
                          projection=cartopy.crs.NorthPolarStereo(
                              central_longitude=300.0))

            plot_cube = cube

            # regrid depending on output format
            if settings.OUTFMT in [".eps", ".pdf"]:
                if plot_cube.coord(
                        "latitude").points.shape[0] > 90 or plot_cube.coord(
                            "longitude").points.shape[0] > 360:
                    regrid_size = 1.0
                    print(
                        "Regridding cube for {} output to {} degree resolution"
                        .format(settings.OUTFMT, regrid_size))
                    print("Old Shape {}".format(plot_cube.data.shape))
                    plot_cube = utils.regrid_cube(plot_cube, regrid_size,
                                                  regrid_size)
                    print("New Shape {}".format(plot_cube.data.shape))

            # prettify
            ax.gridlines()  #draw_labels=True)
            ax.add_feature(cartopy.feature.LAND,
                           zorder=0,
                           facecolor="0.9",
                           edgecolor="k")
            ax.coastlines()
            ax.set_boundary(circle, transform=ax.transAxes)

            if season == "SOS":
                cmap = settings.COLOURMAP_DICT["phenological_r"]
            elif season == "EOS":
                cmap = settings.COLOURMAP_DICT["phenological"]

            norm = mpl.cm.colors.BoundaryNorm(BOUNDS, cmap.N)
            mesh = iris.plot.pcolormesh(plot_cube,
                                        cmap=cmap,
                                        norm=norm,
                                        axes=ax)

            # # read in sites
            if season == "EOS":
                pass
            elif season == "SOS":
                lake_locations = read_us_phenocam(
                    os.path.join(DATALOC, "lake_coords.csv"))
                # scatter
                COL = "chartreuse"
                ax.scatter(lake_locations[1],
                           lake_locations[0],
                           c=COL,
                           s=100,
                           edgecolor="k",
                           transform=cartopy.crs.Geodetic(),
                           zorder=10)
                COL = "m"
                # Harvard Forest - 2019
                ax.scatter(-72.17,
                           42.54,
                           c=COL,
                           s=100,
                           edgecolor="k",
                           transform=cartopy.crs.Geodetic(),
                           zorder=10)

                # uk box
                COL = "y"
                region = [-10.0, 49.0, 3.0, 60.0]
                ax.plot([region[0], region[0]], [region[1], region[3]],
                        c=COL,
                        ls='-',
                        lw=4,
                        zorder=10,
                        transform=cartopy.crs.PlateCarree())
                ax.plot([region[2], region[2]], [region[1], region[3]],
                        c=COL,
                        ls='-',
                        lw=4,
                        zorder=10,
                        transform=cartopy.crs.PlateCarree())
                ax.plot([region[0], region[2]], [region[1], region[1]],
                        c=COL,
                        ls='-',
                        lw=4,
                        zorder=10,
                        transform=cartopy.crs.Geodetic())
                ax.plot([region[0], region[2]], [region[3], region[3]],
                        c=COL,
                        ls='-',
                        lw=4,
                        zorder=10,
                        transform=cartopy.crs.Geodetic())

            # COL = "k"
            # ax.plot([region[0], region[0]], [region[1], region[3]], c=COL, ls='-', lw=5, zorder=9, transform=cartopy.crs.PlateCarree())
            # ax.plot([region[2], region[2]], [region[1], region[3]], c=COL, ls='-', lw=5, zorder=9, transform=cartopy.crs.PlateCarree())
            # ax.plot([region[0], region[2]], [region[1], region[1]], c=COL, ls='-', lw=5, zorder=9, transform=cartopy.crs.Geodetic())
            # ax.plot([region[0], region[2]], [region[3], region[3]], c=COL, ls='-', lw=5, zorder=9, transform=cartopy.crs.Geodetic())

            # label axes
            ax.text(-0.1,
                    1.0,
                    LABELS[season],
                    fontsize=settings.FONTSIZE,
                    transform=ax.transAxes)

            cb = plt.colorbar(mesh,
                              orientation='horizontal',
                              ticks=BOUNDS[1:-1],
                              drawedges=True,
                              fraction=0.1,
                              pad=0.01,
                              aspect=20,
                              shrink=0.8)
            # prettify
            cb.set_label(label="Anomaly (days)", fontsize=settings.FONTSIZE)
            cb.ax.tick_params(axis='x',
                              labelsize=settings.FONTSIZE,
                              direction='in',
                              size=0)
            cb.set_ticklabels(["{:g}".format(b) for b in BOUNDS[1:-1]])
            cb.outline.set_linewidth(2)
            cb.dividers.set_color('k')
            cb.dividers.set_linewidth(2)

            ax.set_extent([-180, 180, 30, 90], cartopy.crs.PlateCarree())

            for lat in range(30, 100, 10):
                ax.text(180,
                        lat,
                        '{}$^\circ$N'.format(lat),
                        transform=cartopy.crs.Geodetic())

            fig.subplots_adjust(bottom=0.05,
                                top=0.95,
                                left=0.04,
                                right=0.95,
                                wspace=0.02)

            del cube

            #***********************
            # MODIS timeserise
            sos_nh, eos_nh, sprt_nh_orig, falt_nh_orig = read_modis_ts(
                os.path.join(
                    DATALOC, "MODIS.CMG.{}.SOS.EOS.SPRT.FALT.TS.csv".format(
                        settings.YEAR)))

            dummy, sos_nh = utils.calculate_climatology_and_anomalies_1d(
                sos_nh, 2000, 2010)
            dummy, eos_nh = utils.calculate_climatology_and_anomalies_1d(
                eos_nh, 2000, 2010)

            dummy, sprt_nh = utils.calculate_climatology_and_anomalies_1d(
                sprt_nh_orig, 2000, 2010)
            dummy, falt_nh = utils.calculate_climatology_and_anomalies_1d(
                falt_nh_orig, 2000, 2010)

            ax = plt.axes([0.15, 0.73, 0.75, 0.23])
            if season == "SOS":
                label = "(a) Start of Season"
                anomalies = [
                    "{} SOS Anomaly = -4.3 days".format(settings.YEAR),
                    "{} Spr. T anomaly = 0.19 ".format(settings.YEAR) +
                    r'$^{\circ}$' + "C"
                ]

                plot_modis_ts(ax, sos_nh, sprt_nh, sprt_nh_orig, label,
                              anomalies, LEGEND_LOC)

            elif season == "EOS":
                label = "(b) End of Season"
                anomalies = [
                    "{} EOS Anomaly = 2.4 days".format(settings.YEAR),
                    "{} Fall T anomaly = -0.53 ".format(settings.YEAR) +
                    r'$^{\circ}$' + "C"
                ]

                plot_modis_ts(ax, eos_nh, falt_nh, falt_nh_orig, label,
                              anomalies, LEGEND_LOC)

            plt.savefig(settings.IMAGELOC + "PHEN_modis_{}_{}{}".format(
                settings.YEAR, season, settings.OUTFMT))

        del cubelist

#***********************
# US timeseries - 2018
    if True:
        fig = plt.figure(figsize=(8, 9.5))
        plt.clf()

        modis_sos, modis_eos, pheno_sos, pheno_eos = read_us_phenocam_csv(
            os.path.join(DATALOC, "Richardson Data for SOC 2019 Figures.csv"))

        # images
        ax = plt.axes([0.01, 0.66, 0.49, 0.3])
        plot_images(ax, "HarvardForest_20190511.jpg")
        ax = plt.axes([0.5, 0.66, 0.49, 0.3])
        plot_images(ax, "HarvardForest_20191024.jpg")

        # timeseries
        ax = plt.axes([0.11, 0.35, 0.84, 0.3])
        plot_us_phenocam(ax, modis_eos, pheno_eos, sos=False)
        #        ax.text(0.05, 0.85, "(a)", transform=ax.transAxes, fontsize=settings.FONTSIZE)
        ax.set_ylim([275, 369])
        plt.setp(ax.get_xticklabels(), visible=False)

        ax = plt.axes([0.11, 0.05, 0.84, 0.3])
        plot_us_phenocam(ax, modis_sos, pheno_sos)
        #        ax.text(0.05, 0.85, "(b)", transform=ax.transAxes, fontsize=settings.FONTSIZE)
        ax.set_ylim([101, 144])

        fig.text(0.02,
                 0.97,
                 "(a)",
                 transform=ax.transAxes,
                 fontsize=settings.FONTSIZE)
        fig.text(0.02,
                 0.3,
                 "Day of year",
                 rotation="vertical",
                 fontsize=settings.FONTSIZE)
        plt.savefig(
            settings.IMAGELOC +
            "PHEN_UStimeseries_{}{}".format(settings.YEAR, settings.OUTFMT))
        plt.close()

    #***********************
    # US timeseries - 2018
    if False:
        fig = plt.figure(figsize=(8, 7))
        plt.clf()

        modis_sos, modis_eos, pheno_sos, pheno_eos = read_us_phenocam_csv(
            os.path.join(DATALOC, "Richardson Data for SOC 2019 Figures.csv"))

        # timeseries
        ax = plt.axes([0.11, 0.5, 0.64, 0.45])
        plot_us_phenocam(ax, modis_eos, pheno_eos, sos=False)
        ax.text(0.05,
                0.85,
                "(c)",
                transform=ax.transAxes,
                fontsize=settings.FONTSIZE)
        ax.set_ylim([275, 369])
        plt.setp(ax.get_xticklabels(), visible=False)
        ax = plt.axes([0.75, 0.5, 0.25, 0.4])
        plot_images(ax, "HarvardForest_20191024.jpg")

        ax = plt.axes([0.11, 0.05, 0.64, 0.45])
        plot_us_phenocam(ax, modis_sos, pheno_sos)
        ax.text(0.05,
                0.85,
                "(d)",
                transform=ax.transAxes,
                fontsize=settings.FONTSIZE)
        ax.set_ylim([101, 144])
        ax = plt.axes([0.75, 0.05, 0.25, 0.4])
        plot_images(ax, "HarvardForest_20190511.jpg")

        fig.text(0.02,
                 0.4,
                 "Day of year",
                 rotation="vertical",
                 fontsize=settings.FONTSIZE)
        plt.savefig(
            settings.IMAGELOC +
            "PHEN_UStimeseries_{}{}".format(settings.YEAR, settings.OUTFMT))
        plt.close()

    #***********************
    # UK timeseries - 2018
    if True:
        from matplotlib.ticker import MultipleLocator
        majorLocator = MultipleLocator(5)

        fig = plt.figure(figsize=(8, 9.5))
        plt.clf()

        # images
        ax = plt.axes([0.01, 0.66, 0.48, 0.3])
        plot_images(ax, "Sarah Burgess first leaf.jpg")
        ax = plt.axes([0.5, 0.66, 0.48, 0.3])
        plot_images(ax, "Judith Garforth oak bare tree 2019.jpg")

        sos_uk, eos_uk = read_modis_uk_ts(
            os.path.join(
                DATALOC, "MODIS.CMG.{}.SOS.EOS.SPRT.FALT.TS.UK_DH.csv".format(
                    settings.YEAR)))
        oak_sos, oak_eos = read_uk_oak_csv(
            os.path.join(DATALOC, "UK_Oakleaf_data.csv"))

        # timeseries
        ax = plt.axes([0.11, 0.35, 0.84, 0.3])
        utils.plot_ts_panel(ax, [oak_eos, eos_uk],
                            "-",
                            "phenological",
                            loc="center left")
        #        ax.text(0.05, 0.85, "(c)", transform=ax.transAxes, fontsize=settings.FONTSIZE)
        ax.set_ylim([210, 354])
        plt.setp(ax.get_xticklabels(), visible=False)
        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        ax.xaxis.set_major_locator(majorLocator)

        # naughtily, manually tweak the upper oak plot
        for line in ax.get_lines():
            if line.get_color() == "g":
                line.set_color("#d95f0e")
        leg = ax.get_legend()
        for line in leg.get_lines():
            if line.get_color() == "g":
                line.set_color("#d95f0e")

        ax = plt.axes([0.11, 0.05, 0.84, 0.3])
        utils.plot_ts_panel(ax, [oak_sos, sos_uk],
                            "-",
                            "phenological",
                            loc="center left")
        #        ax.text(0.05, 0.85, "(d)", transform=ax.transAxes, fontsize=settings.FONTSIZE)
        ax.set_ylim([66, 132])
        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        ax.xaxis.set_major_locator(majorLocator)

        fig.text(0.02,
                 0.97,
                 "(b)",
                 transform=ax.transAxes,
                 fontsize=settings.FONTSIZE)
        fig.text(0.02,
                 0.3,
                 "Day of year",
                 rotation="vertical",
                 fontsize=settings.FONTSIZE)

        plt.savefig(
            settings.IMAGELOC +
            "PHEN_UKtimeseries_{}{}".format(settings.YEAR, settings.OUTFMT))
        plt.close()

    #***********************
    # Lake Boxplot
    if True:

        import pandas as pd

        df = pd.read_csv(DATALOC + "LakeData_forRobert.csv")

        # rename columns
        cols = []
        for col in df.columns:
            if len(col.split()) >= 2:
                df.rename(columns={col: col.split()[0]}, inplace=True)
                cols += [col.split()[0]]

        fig = plt.figure(figsize=(8, 7))
        plt.clf()
        ax = plt.axes([0.1, 0.25, 0.89, 0.74])
        df.boxplot(
            column=cols,
            ax=ax,
            grid=False,
        )

        # messily pull out 2019
        this_year = df.iloc[-1]
        this_year = this_year.to_frame()
        plt.plot(np.arange(11) + 1, this_year[19][1:], "ro")

        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
            tick.label.set_rotation("vertical")

        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        utils.thicken_panel_border(ax)

        plt.ylabel("Day of year", fontsize=settings.FONTSIZE)
        plt.savefig(
            settings.IMAGELOC +
            "PHEN_lakes_boxplot_{}{}".format(settings.YEAR, settings.OUTFMT))
        plt.close()

    return  # run_all_plots
Пример #21
0
def run_all_plots():

    if False:
        #************************************************************************
        # Filled Timeseries
        #************************************************************************

        moderate, severe, extreme = read_data(DATALOC +
                                              "dry_areas_bams_2018_series.csv")

        plt.clf()

        # main panel
        ax1 = plt.axes([0.1, 0.1, 0.85, 0.8])

        ax1.fill_between(moderate.times,
                         0,
                         moderate.data,
                         color="yellow",
                         label="Moderate (<-2)")
        ax1.fill_between(severe.times,
                         0,
                         severe.data,
                         color="orange",
                         label="Severe (<-3)")
        ax1.fill_between(extreme.times,
                         0,
                         extreme.data,
                         color="red",
                         label="Extreme (<-4)")

        ax1.set_ylabel("% Area", fontsize=settings.FONTSIZE)

        ax1.legend(loc="upper left",
                   ncol=1,
                   frameon=False,
                   prop={'size': settings.LEGEND_FONTSIZE},
                   labelspacing=0.1,
                   columnspacing=0.5)

        utils.thicken_panel_border(ax1)
        for tick in ax1.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for tick in ax1.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        minor_tick_interval = 1
        minorLocator = MultipleLocator(minor_tick_interval)
        ax1.xaxis.set_minor_locator(minorLocator)
        ax1.set_xlim([1950, int(settings.YEAR) + 2])
        ax1.set_ylim([None, 44])

        # inset panel
        ax2 = plt.axes([0.7, 0.7, 0.29, 0.29])

        ax2.fill_between(moderate.times[-12:],
                         0,
                         moderate.data[-12:],
                         color="yellow",
                         label="Moderate (<-2)")
        ax2.fill_between(severe.times[-12:],
                         0,
                         severe.data[-12:],
                         color="orange",
                         label="Severe (<-3)")
        ax2.fill_between(extreme.times[-12:],
                         0,
                         extreme.data[-12:],
                         color="red",
                         label="Extreme (<-4)")

        utils.thicken_panel_border(ax2)
        for tick in ax2.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE * 0.7)
        for tick in ax2.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE * 0.7)

        ax2.set_xlim([int(settings.YEAR), int(settings.YEAR) + 1])
        ax2.set_xticks(np.arange(2017, 2018, 1. / 12.))
        ax2.set_xticklabels(
            ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"])
        ax2.set_ylim([None, 34])
        ax2.set_xlim(
            [float(settings.YEAR) - 0.09,
             float(settings.YEAR) + 0.99])
        ax2.text(int(settings.YEAR) + 0.1, 27, settings.YEAR)

        plt.savefig(settings.IMAGELOC + "DGT_ts{}".format(settings.OUTFMT))
        plt.close()

    #************************************************************************
    # Anomaly Map
    #************************************************************************
    # Maps for selected years

    if True:

        cube_list = iris.load(
            DATALOC +
            "BAMS.scPDSI.cru.4.04.2020.early.GLOBAL.annual.mean.2018.2019.nc")

        cube = cube_list[0]
        cube.coord('latitude').guess_bounds()
        cube.coord('longitude').guess_bounds()

        bounds = [-100, -4, -3, -2, -1, 0, 1, 2, 3, 4, 100]

        # select the year - plot 2019 (cube[1])

        utils.plot_smooth_map_iris(
            settings.IMAGELOC +
            "DGT_{}_rel_1901-{}".format(settings.YEAR, settings.YEAR),
            cube[1],
            settings.COLOURMAP_DICT["hydrological"],
            bounds,
            "Categories relative to 1901-{} (self-calibrating PDSI)".format(
                settings.YEAR),
            cb_extra=["Dry", "Wet"],
            contour=True)
        utils.plot_smooth_map_iris(
            settings.IMAGELOC +
            "p2.1_DGT_{}_rel_1901-{}".format(settings.YEAR, settings.YEAR),
            cube[1],
            settings.COLOURMAP_DICT["hydrological"],
            bounds,
            "Categories relative to 1901-{} (self-calibrating PDSI)".format(
                settings.YEAR),
            figtext="(t) Drought (self-calibrating PDSI)",
            cb_extra=["Dry", "Wet"],
            contour=True,
            save_netcdf_filename="{}DGT_for_NOAA_{}.nc".format(
                DATALOC, dt.datetime.strftime(dt.datetime.now(), "%d-%b-%Y")))

        # plot 2019-2018

        newcube = cube[1] - cube[0]
        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "DGT_{}-{}_rel_1901-{}".format(
                settings.YEAR,
                int(settings.YEAR) - 1, settings.YEAR),
            newcube,
            settings.COLOURMAP_DICT["hydrological"],
            bounds,
            "Change in Categories from {} to {} (self-calibrating PDSI)".
            format(int(settings.YEAR) - 1, settings.YEAR),
            cb_extra=["Dry", "Wet"])

    if False:
        # from 2015 report

        # select the last year
        cube_list = []
        YEARS = [1982, 1997]
        for year in YEARS:

            loc, = np.where(cube.coord("time").points == year)
            cube_list += [cube[loc][0]]

        utils.plot_smooth_map_iris_multipanel(
            settings.IMAGELOC +
            "DGR_{}_{}_{}".format(settings.YEAR, YEARS[0], YEARS[1]),
            cube_list,
            settings.COLOURMAP_DICT["hydrological"],
            bounds,
            "Categories relative to 1901-2015 (self-calibrating PSDI)",
            shape=(2, 1),
            title=[str(y) for y in YEARS],
            figtext=["(a)", "(b)"])

        # select the last year
        cube_list = []
        YEARS = [1985, 1987]
        for year in YEARS:

            loc, = np.where(cube.coord("time").points == year)
            cube_list += [cube[loc][0]]

        utils.plot_smooth_map_iris_multipanel(
            settings.IMAGELOC +
            "DGR_{}_{}_{}".format(settings.YEAR, YEARS[0], YEARS[1]),
            cube_list,
            settings.COLOURMAP_DICT["hydrological"],
            bounds,
            "Categories relative to 1901-2015 (self-calibrating PSDI)",
            shape=(2, 1),
            title=[str(y) for y in YEARS],
            figtext=["(a)", "(b)"])

    return  # run_all_plots
Пример #22
0
def run_all_plots():

    #************************************************************************
    # Global Anomaly map

    cube = read_map(
        DATALOC + "tco_omimls_anomaly_{}.txt".format(settings.YEAR),
        "TCO_anom", "DU")

    bounds = np.array([-100, -4, -3, -2, -1, 0, 1, 2, 3, 4, 100])
    bounds = np.array(
        [-100, -1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1.0, 100])

    utils.plot_smooth_map_iris(settings.IMAGELOC +
                               "TCO_anomaly_{}".format(settings.YEAR),
                               cube,
                               settings.COLOURMAP_DICT["composition"],
                               bounds,
                               "Anomalies from 2004-08 (DU)",
                               contour=True)
    utils.plot_smooth_map_iris(
        settings.IMAGELOC + "p2.1_TCO_anomaly_{}".format(settings.YEAR),
        cube,
        settings.COLOURMAP_DICT["composition"],
        bounds,
        "Anomalies from 2004-08 (DU)",
        figtext="(aa) OMI/MLS Tropospheric Column Ozone",
        contour=True)

    #************************************************************************
    # Global Trend map
    cube = read_map(DATALOC + "tco_omimls_trends_{}.txt".format(settings.YEAR),
                    "TCO_trend", "DU")

    bounds = np.array([-100, -3, -2, -1, -0.5, 0, 0.5, 1, 2, 3, 100])
    #    utils.plot_smooth_map_iris(settings.IMAGELOC + "TCO_trend_{}".format(settings.YEAR), cube, settings.COLOURMAP_DICT["composition"], bounds, "(DU per decade)")

    sig_lats, sig_lons, sig_data = read_significance(
        DATALOC + "tco_omimls_trends_{}.txt".format(settings.YEAR), DATALOC +
        "tco_omimls_trends_95pct_signficance_{}.txt".format(settings.YEAR))
    # use local adapted routine.
    plot_smooth_map_iris(settings.IMAGELOC +
                         "TCO_trend_significance_{}".format(settings.YEAR),
                         cube,
                         settings.COLOURMAP_DICT["composition"],
                         bounds,
                         "(DU per decade)",
                         scatter=(sig_lons, sig_lats, sig_data))

    #************************************************************************
    # Timeseries
    # monthly_global, annual_global, monthly_NH, annual_NH, monthly_SH, annual_SH = read_data(DATALOC + "OMI_MLS_trop_ozone_burden_2004_2015.txt")

    monthly_global = read_data(
        DATALOC + "BAMS_SOTC_TROPOSPHERIC_OZONE_TG_60Sto60N_{}.txt".format(
            settings.YEAR), "mg")
    monthly_SH = read_data(
        DATALOC +
        "BAMS_SOTC_TROPOSPHERIC_OZONE_TG_0to60S_{}.txt".format(settings.YEAR),
        "msh")
    monthly_NH = read_data(
        DATALOC +
        "BAMS_SOTC_TROPOSPHERIC_OZONE_TG_0to60N_{}.txt".format(settings.YEAR),
        "mnh")

    annual_global = read_data(
        DATALOC +
        "BAMS_SOTC_TROPOSPHERIC_OZONE_TG_RUNNING_MEAN_60Sto60N_{}.txt".format(
            settings.YEAR), "ag")
    annual_SH = read_data(
        DATALOC +
        "BAMS_SOTC_TROPOSPHERIC_OZONE_TG_RUNNING_MEAN_0to60S_{}.txt".format(
            settings.YEAR), "ash")
    annual_NH = read_data(
        DATALOC +
        "BAMS_SOTC_TROPOSPHERIC_OZONE_TG_RUNNING_MEAN_0to60N_{}.txt".format(
            settings.YEAR), "anh")

    minor_tick_interval = 1
    minorLocator = MultipleLocator(minor_tick_interval)
    COLOURS = settings.COLOURS["composition"]

    fig = plt.figure(figsize=(8, 6))
    ax = plt.axes([0.14, 0.07, 0.84, 0.90])

    plt.plot(monthly_global.times,
             monthly_global.data,
             'k',
             ls='-',
             label=r"1.79$\pm$0.47 Tg yr$^{-1}$",
             lw=LW)
    plt.plot(annual_global.times, annual_global.data, 'k', ls='--', lw=LW)
    plt.text(2004,
             250,
             "60" + r'$^{\circ}$' + "S - 60" + r'$^{\circ}$' + "N",
             va='center',
             color='k',
             fontsize=settings.FONTSIZE)

    plt.plot(monthly_NH.times,
             monthly_NH.data,
             'r',
             ls='-',
             label=r"0.89$\pm$0.39 Tg yr$^{-1}$",
             lw=LW)
    plt.plot(annual_NH.times, annual_NH.data, 'r', ls='--', lw=LW)
    plt.text(2004,
             180,
             "0" + r'$^{\circ}$' + " - 60" + r'$^{\circ}$' + "N",
             va='center',
             color='r',
             fontsize=settings.FONTSIZE)

    plt.plot(monthly_SH.times,
             monthly_SH.data,
             'c',
             ls='-',
             label=r"0.90$\pm$0.46 Tg yr$^{-1}$",
             lw=LW)
    plt.plot(annual_SH.times, annual_SH.data, 'c', ls='--', lw=LW)
    plt.text(2004,
             110,
             "60" + r'$^{\circ}$' + "S - 0" + r'$^{\circ}$' + "",
             va='center',
             color='c',
             fontsize=settings.FONTSIZE)

    ax.legend(loc=LEGEND_LOC,
              ncol=1,
              frameon=False,
              prop={'size': settings.LEGEND_FONTSIZE},
              labelspacing=0.1,
              columnspacing=0.5)

    # prettify
    ax.xaxis.set_minor_locator(minorLocator)
    utils.thicken_panel_border(ax)

    fig.text(0.04,
             0.5,
             "Tropospheric Ozone\n(Tg)",
             va='center',
             rotation='vertical',
             ha="center",
             fontsize=settings.FONTSIZE)

    plt.xlim([2003.5, int(settings.YEAR) + 1.5])
    plt.ylim([90, 340])
    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(settings.FONTSIZE)
    for tick in ax.xaxis.get_major_ticks():
        tick.label.set_fontsize(settings.FONTSIZE)

    plt.savefig(settings.IMAGELOC + "TCO_ts{}".format(settings.OUTFMT))
    plt.close()

    return  # run_all_plots
Пример #23
0
def run_all_plots():

    #***************
    # Anomaly Scatter map
    anomalies = read_lakes(DATALOC +
                           "DATA_StateOfTheClimate_WaterLevelsAnom_v2.csv")

    bounds = [-2, -1, -0.75, -0.50, -0.25, 0, 0.25, 0.50, 0.75, 1, 2]

    lons = np.arange(-90, 120, 30)
    lats = np.arange(-180, 210, 30)
    dummy = np.ma.zeros((len(lats), len(lons)))
    dummy.mask = np.ones(dummy.shape)

    cube = utils.make_iris_cube_2d(dummy, lats, lons, "blank", "m")

    utils.plot_smooth_map_iris(settings.IMAGELOC + "LWL_anomaly", cube, settings.COLOURMAP_DICT["hydrological"], \
                                   bounds, "Anomalies from 1992-2002 (m)", \
                                   scatter=[anomalies[1], anomalies[0], anomalies[2]], figtext="", title="")
    utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_LWL_{}_anomaly".format(settings.YEAR), cube, settings.COLOURMAP_DICT["hydrological"], \
                                   bounds, "Anomalies from 1992-2002 (m)", \
                                   scatter=[anomalies[1], anomalies[0], anomalies[2]], figtext="(m) Lake Water Level", title="")

    #***************
    # multi-panel time series
    indata = read_continuous_csv(
        os.path.join(
            DATALOC,
            "DATA_StateOfTheLakes_WaterLevelAnomTimeSeries_sub_v1.csv"))
    names = np.array([d.name for d in indata])

    lake_order = [
        "Huron", "Superior", "Balkhash", "Tanganyika", "Caspian Sea",
        "Large Aral Sea", "Urmia", "Rukwa"
    ]

    # match HUM plot size

    fig, axes = plt.subplots(nrows=2, ncols=4, figsize=(16, 8), sharex=True)

    counter = 0
    for row in axes:
        for ax in row:

            lake, = np.where(names == lake_order[counter])[0]
            lake = indata[lake]

            utils.thicken_panel_border(ax)
            ax.plot(lake.times, lake.data, "k-")

            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
            for tick in ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

            ax.xaxis.set_major_locator(mdates.YearLocator(10))
            ax.xaxis.set_minor_locator(mdates.YearLocator(1))

            ax.text(0.1,
                    0.9,
                    lake.name,
                    fontsize=settings.FONTSIZE,
                    transform=ax.transAxes)

            ylim = ax.get_ylim()
            ax.set_ylim([ylim[0], ylim[1] * 1.2])

            counter += 1

    fig.text(0.01,
             0.5,
             "Lake Level (m)",
             rotation="vertical",
             va="center",
             fontsize=settings.FONTSIZE)
    fig.subplots_adjust(left=0.07,
                        right=0.99,
                        bottom=0.05,
                        top=0.99,
                        hspace=0.001)
    plt.savefig(settings.IMAGELOC +
                "LWL_ts_{}{}".format(settings.YEAR, settings.OUTFMT))

    #***************
    # Lake Cutouts

    EXTENTS = {
        "GL": (86, 45, [-93, -78, 41, 49]),
        "RU": (62, 42, [43, 81, 35, 48]),
        "AF": (31, -6, [28.5, 33, -10, -3])
    }

    for region in ["GL", "RU", "AF"]:
        if region == "AF":
            fig = plt.figure(figsize=(6, 8))
        elif region == "RU":
            fig = plt.figure(figsize=(18, 8))
        elif region == "GL":
            fig = plt.figure(figsize=(12, 8))

        plt.clf()
        ax = plt.axes([0.05, 0.05, 0.9, 0.9],
                      projection=cartopy.crs.PlateCarree(
                          central_longitude=EXTENTS[region][0]))

        ax.set_extent(EXTENTS[region][2], cartopy.crs.PlateCarree())

        ax.add_feature(cartopy.feature.LAND.with_scale('10m'),
                       zorder=0,
                       facecolor="0.75",
                       edgecolor="k")
        ax.add_feature(cartopy.feature.OCEAN.with_scale('10m'),
                       zorder=0,
                       facecolor="#e0ffff",
                       edgecolor="k")
        ax.add_feature(cartopy.feature.LAKES.with_scale('10m'),
                       zorder=0,
                       facecolor="#e0ffff",
                       edgecolor="k")
        ax.add_feature(cartopy.feature.RIVERS.with_scale('10m'),
                       zorder=0,
                       edgecolor="#e0ffff")
        ax.coastlines(resolution="10m", linewidth=0.5)

        # add other features
        gl = ax.gridlines(draw_labels=True)
        gl.xlabel_style = {'size': settings.FONTSIZE}
        gl.ylabel_style = {'size': settings.FONTSIZE}

        # add labels
        if region == "AF":
            ax.text(30,
                    -5,
                    "Tanganyika",
                    fontsize=settings.FONTSIZE,
                    transform=cartopy.crs.Geodetic())
            ax.text(32,
                    -7.5,
                    "Rukwa",
                    fontsize=settings.FONTSIZE,
                    transform=cartopy.crs.Geodetic())
        elif region == "RU":
            ax.text(46,
                    38,
                    "Urmia",
                    fontsize=settings.FONTSIZE,
                    transform=cartopy.crs.Geodetic())
            ax.text(52,
                    44,
                    "Caspian Sea",
                    fontsize=settings.FONTSIZE,
                    transform=cartopy.crs.Geodetic())
            ax.text(60.5,
                    45,
                    "Large Aral Sea",
                    fontsize=settings.FONTSIZE,
                    transform=cartopy.crs.Geodetic())
            ax.text(75,
                    45.5,
                    "Balkhash",
                    fontsize=settings.FONTSIZE,
                    transform=cartopy.crs.Geodetic())
        elif region == "GL":
            ax.text(-91,
                    46.2,
                    "Superior",
                    fontsize=settings.FONTSIZE,
                    transform=cartopy.crs.Geodetic())
            ax.text(-89,
                    42,
                    "Michigan",
                    fontsize=settings.FONTSIZE,
                    transform=cartopy.crs.Geodetic())
            ax.text(-84.5,
                    44.5,
                    "Huron",
                    fontsize=settings.FONTSIZE,
                    transform=cartopy.crs.Geodetic())

        plt.savefig(settings.IMAGELOC + "LWL_map_{}".format(region) +
                    settings.OUTFMT)
        plt.close()

    return  # run_all_plots
Пример #24
0
                 timeseries.data + uncertainties.data,
                 timeseries.data - uncertainties.data,
                 color="0.75")

slope, upper, lower = utils.median_pairwise_slopes(timeseries.times,
                                                   timeseries.data,
                                                   -99.9,
                                                   sigma=1.0)

plotx, ploty = utils.mpw_plot_points(slope, timeseries.times, timeseries.data)

ax1.plot(plotx, ploty, c="k", ls="-", lw=1)

# prettify
ax1.axhline(0, c='0.5', ls='--')
utils.thicken_panel_border(ax1)
ax1.set_ylim([-1, 1])
ax1.set_xlim([timeseries.times[0] - 1, int(settings.YEAR) + 1])
ax1.set_ylabel("Anomaly (" + r"$^{\circ}$" + "C)")
ax1.text(-0.1, 0.95, "(a)", transform=ax1.transAxes)
ax1.set_title("Global average lake temperature anomalies")
ax1.yaxis.set_ticks_position('left')

minorLocator = MultipleLocator(1)

#***************
# the first hovmuller

# adjust years for plotting
years = np.copy(timeseries.times)
years = np.append(years, years[-1] + 1)
Пример #25
0
def run_all_plots():

    #************************************************************************
    # Read in Australian # Data
    #     aus_lat, aus_lon, aus_anom_8110, aus_trend_79_pres, aus_years, aus_anomalies, aus_clim_8110 = \
    #         read_australia("{}/u_Extracted_ANN_{}_v2.csv".format(DATALOC, settings.YEAR), start_year = 1979)
    # #        read_australia("{}/u_Extracted_ANN_1974_{}_RD.csv".format(DATALOC, settings.YEAR))

    # Timeseries figure
    if True:

        # ERA data
        era5_globe, era5_ocean, era5_land, era5tropics = utils.era5_ts_read(
            settings.REANALYSISLOC, "wnd", annual=True)

        land_era5_clim, land_era5_anoms = utils.calculate_climatology_and_anomalies_1d(
            era5_land, CLIMSTART, 2010)

        land_merra_anoms = utils.read_merra(settings.REANALYSISLOC + "MERRA-2_SfcAnom{}.dat".format(settings.YEAR), \
                                            "wind", "L", anomalies=True)

        jra_actuals, jra_anoms = utils.read_jra55(
            settings.REANALYSISLOC + "JRA-55_ws10m_globalland_ts.txt",
            "windspeed")

        twenty_cr_actuals = utils.read_20cr(
            settings.REANALYSISLOC + "wspd10m.land.txt", "wind speed")
        dummy, twenty_cr_anoms = utils.calculate_climatology_and_anomalies_1d(
            twenty_cr_actuals, CLIMSTART, 2010)

        # Plot timeseries figure
        fig, (ax1, ax2, ax3, ax4) = plt.subplots(4,
                                                 figsize=(8, 13),
                                                 sharex=True)

        print("{} {} {} {} {}".format("name", "mean", "anomaly", "trend/dec",
                                      "N station"))
        for region in all_regions:

            if region.name == "Australia":
                # use the Australian data

                years = aus_years
                anomalies = aus_anomalies

                print(anomalies)

                region.nstat = len(aus_lat)
                region.slope = np.mean(
                    aus_trend_79_pres
                )  # just do the mean of all station slopes
                region.mean = np.mean(aus_clim_8110)

            else:
                # Read in the HadISD annual anomalies
                years, anomalies, m3, m10 = read_hadisd_annual_anomalies(
                    region)

            # Print data for table
            print("{} {} {} {} {}".format(region.name, region.mean,
                                          anomalies[-1], region.slope * 10.,
                                          region.nstat))

            order = anomalies.argsort()
            ranks = order.argsort() + 1

            print("{} highest {} lowest".format(
                len(ranks) - ranks[-1], ranks[-1]))

            # plot data
            if region.fname == "GlobalNoOz":
                ax1.plot(years,
                         anomalies,
                         c=region.color,
                         label=region.name,
                         lw=3,
                         zorder=10)
            else:
                ax1.plot(years,
                         anomalies,
                         c=region.color,
                         label=region.name,
                         lw=2)

            if region.fname == "GlobalNoOz":
                ax3.plot(years, m3, c=region.color, lw=3, zorder=10)
                ax4.plot(years, m10, c=region.color, lw=3)
            elif region.name != "Australia":
                ax3.plot(years, m3, c=region.color, lw=2)
                ax4.plot(years, m10, c=region.color, lw=2)

        # plot reanalyses separately
        ax2.plot(land_era5_anoms.times, land_era5_anoms.data, c=settings.COLOURS["circulation"]["ERA5"], \
                     label="ERA5 (land only)", lw=2)
        ax2.plot(land_merra_anoms.times, land_merra_anoms.data, c=settings.COLOURS["circulation"]["MERRA-2"], \
                     label="MERRA-2 (land only)", lw=2)
        #        ax2.plot(jra_anoms.times, jra_anoms.data, c=settings.COLOURS["circulation"]["JRA-55"], \
        #                             label="JRA-55 (land only)", lw=2)
        ax2.plot(twenty_cr_anoms.times, twenty_cr_anoms.data, c=settings.COLOURS["circulation"]["20CRv3"], \
                     label="20CRv3 (land only)", lw=2)

        # finish off plot
        ax1.axhline(0, c='0.5', ls='--')
        ax2.axhline(0, c='0.5', ls='--')

        ax1.text(0.02,
                 0.9,
                 "(a) In Situ - all Speeds",
                 transform=ax1.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax2.text(0.02,
                 0.9,
                 "(b) Reanalyses - all Speeds",
                 transform=ax2.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax3.text(0.02, 0.9, "(c) In Situ >3 m s"+r'$^{-1}$'+" Winds", transform=ax3.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)
        ax4.text(0.02, 0.9, "(d) In Situ >10 m s"+r'$^{-1}$'+" Winds", transform=ax4.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)

        fig.text(0.02, 0.72, "Wind Anomaly (m s"+r'$^{-1}$'+")", va='center', rotation='vertical', \
                     fontsize=settings.LABEL_FONTSIZE)
        fig.text(0.02, 0.3, "Wind Frequency (% yr"+r'$^{-1}$'+")", va='center', rotation='vertical', \
                     fontsize=settings.LABEL_FONTSIZE)

        ax1.legend(loc="upper right", ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
                       labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=(1.0, 0.9))
        ax2.legend(loc="upper right", ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
                       labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=(1.0, 0.9))

        plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)

        fig.subplots_adjust(right=0.96, top=0.99, bottom=0.03, hspace=0.001)

        for tick in ax4.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        plt.xlim([1970, int(settings.YEAR) + 1])
        ax1.set_ylim([-0.39, 1.0])
        ax2.set_ylim([-0.39, 1.0])
        ax3.set_ylim([23, 68])
        ax4.set_ylim([0, 6.5])

        minorLocator = MultipleLocator(1)
        for ax in [ax1, ax2, ax3, ax4]:
            utils.thicken_panel_border(ax)
            ax.set_yticks(ax.get_yticks()[1:])
            ax.xaxis.set_minor_locator(minorLocator)
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
            ax.yaxis.set_ticks_position('left')

        plt.savefig(settings.IMAGELOC +
                    "WND_land_ts{}".format(settings.OUTFMT))
        plt.close()

    #************************************************************************
    # HadISD Anomaly figure
    if True:

        # Read in HadISD station anomalies
        stn_id, hadisd_lons, hadisd_lats, mean8110, hadisd_anomaly_8110, hadisd_trend_79_pres = read_hadisd_global_summary(
        )

        # combine together
        lats = hadisd_lats
        lons = hadisd_lons
        anom = hadisd_anomaly_8110
        trend = hadisd_trend_79_pres * 10

        # lats = np.append(hadisd_lats, aus_lat)
        # lons = np.append(hadisd_lons, aus_lon)
        # anom = combine_arrays((hadisd_anomaly_8110, aus_anom_8110))
        # trend = combine_arrays((hadisd_trend_79_pres, aus_trend_79_pres)) * 10.

        #    bounds = [-100, -0.8, -0.4, -0.2, -0.1, 0, 0.1, 0.2, 0.4, 0.8, 100]
        bounds = [-100, -0.4, -0.2, -0.1, -0.05, 0, 0.05, 0.1, 0.2, 0.4, 100]
        utils.scatter_plot_map(settings.IMAGELOC + "WND_{}_obs_trend".format(settings.YEAR), trend, \
                                   lons, lats, settings.COLOURMAP_DICT["circulation_r"], bounds, "Trend from {}-{} (m s".format(TRENDSTART, settings.YEAR)+r'$^{-1}$'+" decade"+r'$^{-1}$)')

        bounds = [-100, -1.2, -0.8, -0.4, -0.2, 0, 0.2, 0.4, 0.8, 1.2, 100]
        utils.scatter_plot_map(settings.IMAGELOC + "WND_{}_obs_anomaly".format(settings.YEAR), anom, \
                               lons, lats, settings.COLOURMAP_DICT["circulation_r"], bounds, "Anomalies from {}-2010 (m s".format(CLIMSTART)+r'$^{-1}$)')

        total = float(len(anom.compressed()))
        pos, = np.ma.where(anom > 0)
        neg, = np.ma.where(anom < 0)
        print("Anomalies: positive {:5.3f} negative {:5.3f}".format(
            len(pos) / total,
            len(neg) / total))
        pos, = np.ma.where(anom > 0.5)
        neg, = np.ma.where(anom < -0.5)
        print("Anomalies: positive {:5.3f} negative {:5.3f} (than 0.5)".format(
            len(pos) / total,
            len(neg) / total))
        pos, = np.ma.where(anom > 1.0)
        neg, = np.ma.where(anom < -1.0)
        print("Anomalies: positive {:5.3f} negative {:5.3f} (than 1.0)".format(
            len(pos) / total,
            len(neg) / total))

        total = float(len(trend.compressed()))
        pos, = np.ma.where(trend > 0)
        neg, = np.ma.where(trend < 0)
        print("Trends: positive {:5.3f} negative {:5.3f}".format(
            len(pos) / total,
            len(neg) / total))

    #************************************************************************
    # ERA5 + HadISD Anomaly figure
    if True:
        # Read in ERA anomalies

        cube_list = iris.load(settings.REANALYSISLOC +
                              "era5_ws10_{}01-{}12_ann_ano.nc".format(
                                  settings.YEAR, settings.YEAR))

        cube = cube_list[0]
        cube.coord('latitude').guess_bounds()
        cube.coord('longitude').guess_bounds()

        bounds = [-4, -1.2, -0.8, -0.4, -0.2, 0, 0.2, 0.4, 0.8, 1.2, 4]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "WND_{}_era5_obs_anomaly".format(settings.YEAR), cube[0], \
            settings.COLOURMAP_DICT["circulation_r"], bounds, "Anomalies from {}-2010 (m s".format(CLIMSTART)+r'$^{-1}$)', scatter = (lons, lats, anom))
        utils.plot_smooth_map_iris(settings.IMAGELOC + "WND_{}_era5_anomaly".format(settings.YEAR), cube[0], \
            settings.COLOURMAP_DICT["circulation_r"], bounds, "Anomalies from {}-2010 (m s".format(CLIMSTART)+r'$^{-1}$)')

    #************************************************************************
    # MERRA Anomaly figure
    if True:
        anoms = read_ocean_ncdf(
            DATALOC +
            "rss_wind_trend_anomaly_SOTC_{}_updated.nc".format(settings.YEAR),
            "MERRA2_wind_anomaly_map_{}".format(settings.YEAR))

        bounds = [-40, -1.2, -0.8, -0.4, -0.2, 0, 0.2, 0.4, 0.8, 1.2, 40]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "WND_merra2_anomaly", anoms, settings.COLOURMAP_DICT["circulation_r"], bounds,\
                                       "Anomalies from 1981-2010 (m s"+r'$^{-1}$'+")")

    #************************************************************************
    # MERRA + HadISD Anomaly figure

    if True:
        # Read in MERRA anomalies

        cube_list = iris.load(
            settings.REANALYSISLOC +
            "MERRA-2_SfcAnom_{}.nc".format(settings.YEAR),
            "10m Wind Speed Anomaly (1981-2010)")

        cube = cube_list[0]
        cube.coord('latitude').guess_bounds()
        cube.coord('longitude').guess_bounds()

        bounds = [-4, -1.2, -0.8, -0.4, -0.2, 0, 0.2, 0.4, 0.8, 1.2, 4]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "WND_{}_merra_obs_anomaly".format(settings.YEAR), cube[0], \
                                       settings.COLOURMAP_DICT["circulation_r"], bounds, \
                                       "Anomalies from {}-2010 (m s".format(CLIMSTART)+r'$^{-1}$)', scatter=(lons, lats, anom))
        utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_WND_{}_merra_obs_anomaly".format(settings.YEAR), cube[0], \
                                       settings.COLOURMAP_DICT["circulation_r"], bounds, \
                                       "Anomalies from {}-2010 (m s".format(CLIMSTART)+r'$^{-1}$)', figtext="(v) Surface Winds", scatter=(lons, lats, anom))
        utils.plot_smooth_map_iris(settings.IMAGELOC + "WND_{}_merra_anomaly".format(settings.YEAR), cube[0], \
                                       settings.COLOURMAP_DICT["circulation_r"], bounds, \
                                       "Anomalies from {}-2010 (m s".format(CLIMSTART)+r'$^{-1}$)')

    #************************************************************************
    # MERRA/RSS ocean + HadISD Anomaly figure
    if True:
        # Read in MERRA/RSS trends
        anomalies = read_ocean_ncdf(
            DATALOC +
            "rss_wind_trend_anomaly_SOTC_{}_updated.nc".format(settings.YEAR),
            "Merged_wind_anomaly_map_{}".format(settings.YEAR))

        bounds = [-4, -1.2, -0.8, -0.4, -0.2, 0, 0.2, 0.4, 0.8, 1.2, 4]
        utils.plot_smooth_map_iris(settings.IMAGELOC + "WND_{}_merra-rss_anomaly".format(settings.YEAR), \
                                       anomalies, settings.COLOURMAP_DICT["circulation_r"], bounds, \
                                       "Anomalies from 1981-2010 (m s"+r'$^{-1}$)')
        utils.plot_smooth_map_iris(settings.IMAGELOC + "WND_{}_merra-rss_obs_anomaly".format(settings.YEAR), \
                                       anomalies, settings.COLOURMAP_DICT["circulation_r"], bounds, \
                                       "Anomalies from 1981-2010 (m s"+r'$^{-1}$)',
                                   scatter=(lons, lats, anom))
        utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_WND_{}_merra-rss_obs_anomaly".format(settings.YEAR), \
                                       anomalies, settings.COLOURMAP_DICT["circulation_r"], bounds, \
                                       "Anomalies from 1981-2010 (m s"+r'$^{-1}$)', figtext="(v) Surface Winds", scatter=(lons, lats, anom))

    #************************************************************************
    # Ocean timeseries
    if True:

        satellite = read_ts_cube(
            DATALOC +
            "rss_wind_trend_anomaly_SOTC_{}.nc".format(settings.YEAR),
            "RSS_wind_global_annual_anom_ts", "Satellite MW Radiometers")
        satellite_clim, satellite_anom = utils.calculate_climatology_and_anomalies_1d(
            satellite, 1988, 2010)

        #    print("NO IN SITU OCEAN DATA FOR 2016, using 2015 data")
        #    nocs = read_ts_cube(DATALOC + "NOCSv2.0_oceanW_5by5_8110anoms_areaTS_FEB2016.nc", "Globally Average 70S-70N", "NOCSv2.0")
        #    WASwind = read_ts_cube(DATALOC + "waswind_v1_0_1.monthly_areaTS_19502011.nc","Globally Averaged Anomalies 70S-70N", "WASwind")
        #    print("FIXING WASWIND TIMES - DATAFILE HAS WRONG DESCRIPTOR")
        #    WASwind.times = WASwind.times - (1973-1950)

        jra_actuals, jra_anoms = utils.read_jra55(
            settings.REANALYSISLOC + "JRA-55_ws10m_globalocean_ts.txt", "wind")

        era5_globe, era5_ocean, era5_land, era5tropics = utils.era5_ts_read(
            settings.REANALYSISLOC, "wnd", annual=True)
        ocean_era5_clim, ocean_era5_anoms = utils.calculate_climatology_and_anomalies_1d(
            era5_ocean, 1988, 2010)

        merra_anoms = utils.read_merra(
            settings.REANALYSISLOC +
            "MERRA-2_SfcAnom{}.dat".format(settings.YEAR),
            "wind",
            "O",
            anomalies=True)

        twenty_cr_actuals = utils.read_20cr(
            settings.REANALYSISLOC + "wspd10m.ocean.txt", "wind speed")
        dummy, twenty_cr_anoms = utils.calculate_climatology_and_anomalies_1d(
            twenty_cr_actuals, 1988, 2010)

        fig, (ax1) = plt.subplots(1, figsize=(8, 5), sharex=True)

        # Satellite
        #    utils.plot_ts_panel(ax1, [satellite_anom], "-", "circulation", loc=LEGEND_LOC, bbox=BBOX)

        # In Situ
        #    utils.plot_ts_panel(ax2, [nocs, WASwind], "-", "circulation", loc=LEGEND_LOC, bbox=BBOX)
        #    ax2.set_ylabel("Anomaly (m s"+r'$^{-1}$'+")", fontsize = settings.FONTSIZE)

        # Reanalyses & Satellite single panel
        satellite_anom.lw = 4
        satellite_anom.zorder = 10
        utils.plot_ts_panel(
            ax1,
            [satellite_anom, ocean_era5_anoms, merra_anoms, twenty_cr_anoms],
            "-",
            "circulation",
            loc=LEGEND_LOC,
            bbox=BBOX)

        #*******************
        # prettify
        ax1.axhline(0, c='0.5', ls='--')
        plt.ylabel("Wind Anomaly (m s" + r'$^{-1}$' + ")",
                   fontsize=settings.LABEL_FONTSIZE)
        ax1.legend(loc="upper right", ncol=1, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
                       labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=(1.0, 0.99))

        # sort formatting
        plt.xlim([1970, int(settings.YEAR) + 1])

        for tick in ax1.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
    #    for ax in [ax1, ax2, ax3]:
        for ax in [ax1]:
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
            ax.set_ylim([-0.28, 0.45])
            ax.yaxis.set_ticks([-0.2, 0.0, 0.2, 0.4])
            ax.yaxis.set_ticks_position('left')

        # sort labelling
        ax1.text(0.03,
                 0.9,
                 "Satellites & Reanalyses",
                 transform=ax1.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        #    ax2.text(0.03, 0.9, "(b) In Situ", transform=ax2.transAxes, fontsize=settings.LABEL_FONTSIZE)
        #    ax3.text(0.03, 0.9, "(b) Reanalyses", transform=ax3.transAxes, fontsize=settings.LABEL_FONTSIZE

        fig.subplots_adjust(right=0.95, top=0.95, hspace=0.001)

        plt.savefig(settings.IMAGELOC +
                    "WND_ocean_ts{}".format(settings.OUTFMT))

        plt.close()

    #************************************************************************
    # Ocean maps
    if True:
        anoms = read_ocean_ncdf(
            DATALOC +
            "rss_wind_trend_anomaly_SOTC_{}_updated.nc".format(settings.YEAR),
            "RSS_wind_anomaly_map_{}".format(settings.YEAR))

        bounds = [-40, -1.2, -0.8, -0.4, -0.2, 0, 0.2, 0.4, 0.8, 1.2, 40]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "WND_{}_rss_anomaly".format(settings.YEAR), anoms, settings.COLOURMAP_DICT["circulation_r"], bounds,\
                                       "Anomalies from 1981-2010 (m s"+r'$^{-1}$'+")")

    #************************************************************************
    # MERRA/RSS ocean + HadISD Trend figure
    if True:
        # Read in MERRA/RSS trends
        trends = read_ocean_ncdf(
            DATALOC +
            "rss_wind_trend_anomaly_SOTC_{}_updated.nc".format(settings.YEAR),
            "Wind_trend_map")

        bounds = [-4, -0.8, -0.4, -0.2, -0.1, 0, 0.1, 0.2, 0.4, 0.8, 4]
        bounds = [-100, -0.4, -0.2, -0.1, -0.05, 0, 0.05, 0.1, 0.2, 0.4, 100]
        utils.plot_smooth_map_iris(settings.IMAGELOC + "WND_{}_merra-rss_trend".format(settings.YEAR), \
                                       trends, settings.COLOURMAP_DICT["circulation_r"], bounds, \
                                       "Trend from {}-{} (m s".format(TRENDSTART, settings.YEAR)+r'$^{-1}$'+" decade"+r'$^{-1}$)')
        utils.plot_smooth_map_iris(settings.IMAGELOC + "WND_{}_merra-rss_obs_trend".format(settings.YEAR), \
                                       trends, settings.COLOURMAP_DICT["circulation_r"], bounds, \
                                       "Trend from {}-{} (m s".format(TRENDSTART, settings.YEAR)+r'$^{-1}$'+" decade"+r'$^{-1}$)',
                                   scatter=(lons, lats, trend))

    return  # run_all_plots
Пример #26
0
def run_all_plots():

    #************************************************************************
    # Timeseries figures
    if True:

        fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(8, 10), sharex=True)

        UAH, rss, ratpac, raobcore, rich, noaa, jra, merra = read_csv(
            DATALOC + "SotC_AnnTemps_2020_0220_LSTGL.csv")
        #        ssu2, ncar = read_ssu_csv(DATALOC + "2018_LTT_LST_SSU_date0401_SSU.csv")

        eral, erao, eralo = read_era5(DATALOC + "ERA5_TLS_GLOBAL")
        eralo_ann = utils.Timeseries("ERA5",
                                     np.reshape(eralo.times, [-1, 12])[:, 0],
                                     utils.annual_average(eralo.data))

        # Sondes [no RATPAC for 2019]
        utils.plot_ts_panel(ax1, [raobcore, rich],
                            "-",
                            "temperature",
                            loc=LEGEND_LOC)

        # satellites
        utils.plot_ts_panel(ax2, [UAH, noaa, rss],
                            "-",
                            "temperature",
                            loc=LEGEND_LOC)

        # reanalyses
        jra_actuals, jra_anoms = utils.read_jra55(
            settings.REANALYSISLOC + "JRA-55_MSUch4_global_ts.txt",
            "temperature")
        merra_actuals, merra_anoms = utils.read_merra_LT_LS(
            settings.REANALYSISLOC +
            "MERRA2_MSU_Tanom_ann_{}.dat".format(settings.YEAR),
            LS=True)
        utils.plot_ts_panel(ax3, [eralo_ann, jra_anoms, merra_anoms],
                            "-",
                            "temperature",
                            loc=LEGEND_LOC)

        #    ax3.set_ylabel("Anomaly ("+r'$^\circ$'+"C)", fontsize=settings.FONTSIZE)

        # Upper Stratosphere
        #        utils.plot_ts_panel(ax4, [ssu2, ncar], "-", "temperature", loc=LEGEND_LOC)

        # sort formatting
        plt.xlim([1957, raobcore.times[-1] + 1])

        for tick in ax3.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for ax in [ax1, ax2, ax3]:
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

            ax.set_ylim([-1.2, 2.2])

        # sort labelling
        ax1.text(0.02, 0.88, "(a) Radiosondes", transform=ax1.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)
        ax2.text(0.02, 0.88, "(b) Satellites", transform=ax2.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)
        ax3.text(0.02, 0.88, "(c) Reanalyses", transform=ax3.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)

        fig.text(0.01,
                 0.45,
                 "Anomaly (" + r'$^\circ$' + "C)",
                 fontsize=settings.FONTSIZE,
                 rotation="vertical")
        fig.subplots_adjust(right=0.98, top=0.98, bottom=0.04, hspace=0.001)

        plt.savefig(settings.IMAGELOC + "LST_ts{}".format(settings.OUTFMT))

        plt.close()

    #************************************************************************
    # Timeseries figures
    if True:

        fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(8, 10), sharex=True)

        ssu1, ssu1_2, ssu2, ssu2_2, ssu3, ssu3_2 = read_ssu(DATALOC +
                                                            "SSU.dat")

        # SSU3
        utils.plot_ts_panel(ax1, [ssu3, ssu3_2], "-", "temperature", loc="")
        # SSU2
        utils.plot_ts_panel(ax2, [ssu2, ssu2_2], "-", "temperature", loc="")
        # SSU1
        utils.plot_ts_panel(ax3, [ssu1, ssu1_2],
                            "-",
                            "temperature",
                            loc=LEGEND_LOC)

        # sort formatting
        plt.xlim([1957, ssu1.times[-1] + 2])

        for tick in ax3.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for ax in [ax1, ax2, ax3]:
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

            ax.set_ylim([-1.3, 2.2])

        # sort labelling
        ax1.text(0.02, 0.88, "(a) SSU3", transform=ax1.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)
        ax2.text(0.02, 0.88, "(b) SSU2", transform=ax2.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)
        ax3.text(0.02, 0.88, "(c) SSU1", transform=ax3.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)

        fig.text(0.01,
                 0.45,
                 "Anomaly (" + r'$^\circ$' + "C)",
                 fontsize=settings.FONTSIZE,
                 rotation="vertical")
        fig.subplots_adjust(right=0.98, top=0.98, bottom=0.04, hspace=0.001)

        plt.savefig(settings.IMAGELOC + "LST_SSU_ts{}".format(settings.OUTFMT))

        plt.close()

    #************************************************************************
    # Combined Timeseries figures
    if True:

        fig = plt.figure(figsize=(12, 8))

        # manually set up the 10 axes
        w = 0.42
        h = 0.31
        c = 0.51
        ax1 = plt.axes([c - w, 0.99 - h, w, h])
        ax2 = plt.axes([c, 0.99 - h, w, h])
        ax3 = plt.axes([c - w, 0.99 - (2 * h), w, h], sharex=ax1)
        ax4 = plt.axes([c, 0.99 - (2 * h), w, h], sharex=ax2)
        ax5 = plt.axes([c - w, 0.99 - (3 * h), w, h], sharex=ax1)
        ax6 = plt.axes([c, 0.99 - (3 * h), w, h], sharex=ax2)

        UAH, rss, ratpac, raobcore, rich, noaa, jra, merra = read_csv(
            DATALOC + "SotC_AnnTemps_2020_0220_LSTGL.csv")
        #        ssu2, ncar = read_ssu_csv(DATALOC + "2018_LTT_LST_SSU_date0401_SSU.csv")

        eral, erao, eralo = read_era5(DATALOC + "ERA5_TLS_GLOBAL")
        eralo_ann = utils.Timeseries("ERA5",
                                     np.reshape(eralo.times, [-1, 12])[:, 0],
                                     utils.annual_average(eralo.data))

        # update to ERA5.1 during revisions for SotC2019
        era51 = np.genfromtxt(DATALOC + "ERA5_1_update.dat")
        eralo_ann = utils.Timeseries("ERA5", era51[:, 0], era51[:, 1])

        # Sondes [no RATPAC for 2019]
        utils.plot_ts_panel(ax2, [raobcore, rich, ratpac],
                            "-",
                            "temperature",
                            loc=LEGEND_LOC)

        # satellites
        utils.plot_ts_panel(ax4, [UAH, noaa, rss],
                            "-",
                            "temperature",
                            loc=LEGEND_LOC)

        # reanalyses
        jra_actuals, jra_anoms = utils.read_jra55(
            settings.REANALYSISLOC + "JRA-55_MSUch4_global_ts.txt",
            "temperature")
        merra_actuals, merra_anoms = utils.read_merra_LT_LS(
            settings.REANALYSISLOC +
            "MERRA2_MSU_Tanom_ann_{}.dat".format(settings.YEAR),
            LS=True)
        utils.plot_ts_panel(ax6, [eralo_ann, jra_anoms, merra_anoms],
                            "-",
                            "temperature",
                            loc=LEGEND_LOC)

        ssu1, ssu1_2, ssu2, ssu2_2, ssu3, ssu3_2 = read_ssu(DATALOC +
                                                            "SSU.dat")

        # SSU3
        utils.plot_ts_panel(ax1, [ssu3, ssu3_2], "-", "temperature", loc="")
        # SSU2
        utils.plot_ts_panel(ax3, [ssu2, ssu2_2], "-", "temperature", loc="")
        # SSU1
        utils.plot_ts_panel(ax5, [ssu1, ssu1_2],
                            "-",
                            "temperature",
                            loc=LEGEND_LOC)

        # sort labelling
        for ax in [ax2, ax4, ax6]:
            ax.yaxis.tick_right()
            for tick in ax.yaxis.get_major_ticks():
                tick.label2.set_fontsize(settings.FONTSIZE)
        for ax in [ax1, ax3, ax5]:
            ax.yaxis.tick_right()
            ax.yaxis.set_ticks_position('left')

        ax2.text(0.02, 0.88, "(d) Radiosondes", transform=ax2.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)
        ax4.text(0.02, 0.88, "(e) Satellites", transform=ax4.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)
        ax6.text(0.02, 0.88, "(f) Reanalyses", transform=ax6.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)

        ax1.text(0.02, 0.88, "(a) SSU3", transform=ax1.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)
        ax3.text(0.02, 0.88, "(b) SSU2", transform=ax3.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)
        ax5.text(0.02, 0.88, "(c) SSU1", transform=ax5.transAxes, \
                     fontsize=settings.LABEL_FONTSIZE)

        plt.setp([a.get_xticklabels() for a in fig.axes[:-2]], visible=False)

        # sort formatting
        ax1.set_xlim([1957, raobcore.times[-1] + 3])
        ax2.set_xlim([1957, raobcore.times[-1] + 3])

        for ax in [ax5, ax6]:
            for tick in ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)
        for ax in [ax1, ax2, ax3, ax4, ax5, ax6]:
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

            ax.set_ylim([-1.2, 2.2])

        fig.text(0.01,
                 0.55,
                 "Anomaly (" + r'$^\circ$' + "C)",
                 fontsize=settings.FONTSIZE,
                 rotation="vertical")
        fig.subplots_adjust(right=0.98, top=0.98, bottom=0.04, hspace=0.001)

        plt.savefig(settings.IMAGELOC +
                    "LST_combined_ts{}".format(settings.OUTFMT))

        plt.close()

    #************************************************************************
    # Polar Figure
    if False:
        fig, ax1 = plt.subplots(figsize=(8, 5))

        north, south = read_polar(DATALOC +
                                  "polar_data_{}.dat".format(settings.YEAR))

        ax1.plot(north.times, north.data, c="b", ls="-", label=north.name)
        ax1.plot(south.times, south.data, c="r", ls="-", label=south.name)

        ax1.legend(loc=LEGEND_LOC,
                   frameon=False,
                   prop={'size': settings.FONTSIZE})
        ax1.set_xlim([1978, 2018 + 2])
        ax1.set_ylabel("Anomaly (" + r'$^\circ$' + "C)",
                       fontsize=settings.FONTSIZE)

        utils.thicken_panel_border(ax1)

        plt.savefig(settings.IMAGELOC +
                    "LST_polar_ts{}".format(settings.OUTFMT))

        for tick in ax1.yaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for tick in ax1.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)

        plt.close()

    #************************************************************************
    # Polar and QBO Timeseries figures

    # fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(8, 10), sharex=True)

    # north, south, qbo = read_qbo_csv(DATALOC + "SOC_Strat_Data_QBO.csv")

    # noaa_qbo = read_qbo_ncdf(DATALOC + "qbo_noaa.nc", "NOAA v4.0")
    # uah_qbo = read_qbo_ncdf(DATALOC + "qbo_uah.nc", "UAH v6.0")
    # rss_qbo = read_qbo_ncdf(DATALOC + "qbo_rss.nc", "RSS v3.3")

    # utils.plot_ts_panel(ax1, [north], "-", "temperature", loc="")
    # utils.plot_ts_panel(ax2, [south], "-", "temperature", loc="")
    # utils.plot_ts_panel(ax3, [noaa_qbo, uah_qbo, rss_qbo], "-", "temperature", loc="", lw=1)

    # lines3, labels3 = ax3.get_legend_handles_labels()

    # plt.figlegend(lines3, labels3, "lower center", frameon=False, ncol=3, fontsize=settings.FONTSIZE)

    # ax1.set_ylabel("Anomaly ("+r'$^\circ$'+"C)", fontsize=settings.FONTSIZE)
    # ax2.set_ylabel("Anomaly ("+r'$^\circ$'+"C)", fontsize=settings.FONTSIZE)
    # ax3.set_ylabel("QBO Index", fontsize=settings.FONTSIZE)

    # ax1.text(0.02, 0.88, "(a) North Polar Pentad Anomalies", transform=ax1.transAxes, \
    #              fontsize=settings.LABEL_FONTSIZE)
    # ax2.text(0.02, 0.88, "(b) South Polar Pentad Anomalies", transform=ax2.transAxes, \
    #              fontsize=settings.LABEL_FONTSIZE)
    # ax3.text(0.02, 0.88, "(c) QBO from Lower Stratospheric Temperature", transform=ax3.transAxes, \
    #              fontsize=settings.LABEL_FONTSIZE)

    # ax3.text(-0.15, 0.88, "West", transform=ax3.transAxes, fontsize=settings.LABEL_FONTSIZE)
    # ax3.text(-0.15, 0.01, "East", transform=ax3.transAxes, fontsize=settings.LABEL_FONTSIZE)

    # # sort formatting
    # plt.xlim([1978, int(settings.YEAR)+1])

    # for tick in ax3.xaxis.get_major_ticks():
    #     tick.label.set_fontsize(settings.FONTSIZE)
    # for ax in [ax1, ax2, ax3]:
    #     for tick in ax.yaxis.get_major_ticks():
    #         tick.label.set_fontsize(settings.FONTSIZE)

    # ax1.set_ylim([-10, 19])
    # ax2.set_ylim([-10, 23])
    # ax3.set_ylim([-1.1, 1.4])

    # fig.subplots_adjust(right=0.95, top=0.95, hspace=0.001)

    # plt.savefig(settings.IMAGELOC+"LST_qbo_ts{}".format(settings.OUTFMT))

    # plt.close()

    #************************************************************************
    # MERRA Trop and Strat Timeseries figures

    # fourh, threeh, twofiveh, twoh, onefiveh, fourtwoav, oneh, seventy, fifty, thirty, twenty, ten, seventytwentyav = read_merra_monthly(DATALOC + "MERRA2_400_20_temp_anom_1980-{}.txt".format(settings.YEAR))

    # fourtwoav.data = np.ma.masked_where(fourtwoav.times < 1994, fourtwoav.data)
    # seventytwentyav.data = np.ma.masked_where(seventytwentyav.times < 1994, seventytwentyav.data)
    # fourtwoav.times = np.ma.masked_where(fourtwoav.times < 1994, fourtwoav.times)
    # seventytwentyav.times = np.ma.masked_where(seventytwentyav.times < 1994, seventytwentyav.times)

    # fig, (ax1, ax2) = plt.subplots(2, figsize = (8, 8), sharex=True)

    # # trop
    # fit = utils.fit_plot_points(0.025, -50.01, fourtwoav.times)
    # ax1.plot(fourh.times, fit, c="0.5", lw = 2, ls = "-", label = "fit", zorder = 10)
    # utils.plot_ts_panel(ax1, [fourh, threeh, twofiveh, twoh, fourtwoav], "-", "lst", loc = LEGEND_LOC)
    # # strat
    # fit = utils.fit_plot_points(-0.0014, 2.4527, seventytwentyav.times)
    # ax2.plot(fourh.times, fit, c="0.5", lw = 2, ls = "-", label = "fit", zorder = 10)
    # utils.plot_ts_panel(ax2, [seventy, fifty, thirty, twenty, seventytwentyav], "-", "lst", loc = LEGEND_LOC)

    # # sort formatting
    # plt.xlim([1978, fourh.times[-1]+1])
    # ax1.set_ylim([-1.7,1.5])
    # ax2.set_ylim([-2.0,2.7])

    # for tick in ax2.xaxis.get_major_ticks():
    #     tick.label.set_fontsize(settings.FONTSIZE)
    # for ax in [ax1, ax2]:
    #     for tick in ax.yaxis.get_major_ticks():
    #         tick.label.set_fontsize(settings.FONTSIZE)

    # # sort labelling
    # ax1.text(0.02, 0.9, "(a) MERRA-2 Troposphere", transform = ax1.transAxes, fontsize = settings.LABEL_FONTSIZE)
    # ax2.text(0.02, 0.9, "(b) MERRA-2 Stratosphere", transform = ax2.transAxes, fontsize = settings.LABEL_FONTSIZE)

    # ax1.text(0.7, 0.9, "y=0.025x - 50.01", transform = ax1.transAxes, fontsize = settings.LABEL_FONTSIZE*0.8)
    # ax2.text(0.7, 0.9, "y=-0.0014x + 2.4527", transform = ax2.transAxes, fontsize = settings.LABEL_FONTSIZE*0.8)

    # ax1.set_ylabel("Anomaly ("+r'$^\circ$'+"C)", fontsize = settings.FONTSIZE)
    # ax2.set_ylabel("Anomaly ("+r'$^\circ$'+"C)", fontsize = settings.FONTSIZE)

    # fig.subplots_adjust(right = 0.95, top = 0.95, hspace = 0.001)

    # plt.savefig(settings.IMAGELOC+"LST_merra_ts{}".format(settings.OUTFMT))

    # plt.close()

    #************************************************************************
    # Zonal figures

    # fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (8, 6.5), sharey=True)

    # cfsr, merra, era, jra = read_zonal(DATALOC + "TLS_Reanal_zonal_trends_1994-{}.txt".format(settings.YEAR), "R")
    # star, uah, rss = read_zonal(DATALOC + "TLS_Satellite_zonal_trends_1994-{}.txt".format(settings.YEAR), "S")

    # # Reanalyses
    # utils.plot_ts_panel(ax1, [cfsr, merra, era, jra], "--", "temperature", loc = "lower left", ncol = 1)

    # # Satellite
    # utils.plot_ts_panel(ax2, [star, uah, rss], "--", "temperature", loc = "center right", ncol = 1)

    # ax1.axvline(0,color = "0.5", ls = "--")
    # ax2.axvline(0,color = "0.5", ls = "--")

    # # sort formatting
    # plt.ylim([-90,90])
    # ax1.set_ylabel("Latitude", fontsize = settings.LABEL_FONTSIZE)
    # ax1.set_xlabel("Trend ("+r'$^\circ$'+"C decade"+r'$^{-1}$'+")", fontsize = settings.FONTSIZE)
    # ax2.set_xlabel("Trend ("+r'$^\circ$'+"C decade"+r'$^{-1}$'+")", fontsize = settings.FONTSIZE)

    # for tick in ax1.yaxis.get_major_ticks():
    #     tick.label.set_fontsize(settings.FONTSIZE)
    # for ax in [ax1, ax2]:
    #     ax.set_xlim([-0.3,0.6])
    #     ax.set_xticks(np.arange(-0.2,0.8,0.2))
    #     ax.set_yticks(np.arange(-90,120,30))
    #     for tick in ax.xaxis.get_major_ticks():
    #         tick.label.set_fontsize(settings.FONTSIZE)

    # # sort labelling
    # ax1.text(0.02, 0.9, "(a) Radiosondes", transform = ax1.transAxes, fontsize = settings.LABEL_FONTSIZE)
    # ax2.text(0.02, 0.9, "(b) Satellites", transform = ax2.transAxes, fontsize = settings.LABEL_FONTSIZE)

    # fig.subplots_adjust(right = 0.95, top = 0.95, hspace = 0.001)

    # plt.savefig(settings.IMAGELOC+"LST_profiles{}".format(settings.OUTFMT))

    # plt.close()

    #************************************************************************
    # ERA5 Anomaly figure
    if True:
        # Read in ERA anomalies

        cube_list = iris.load(settings.REANALYSISLOC +
                              "era5_tls_{}01-{}12_ann_ano.nc".format(
                                  settings.YEAR, settings.YEAR))

        cube = cube_list[0]
        cube.coord('latitude').guess_bounds()
        cube.coord('longitude').guess_bounds()

        bounds = [-4, -1.2, -0.8, -0.4, -0.2, 0, 0.2, 0.4, 0.8, 1.2, 4]

        utils.plot_smooth_map_iris(settings.IMAGELOC + "LST_{}_anoms_era5".format(settings.YEAR), cube[0], \
                                   settings.COLOURMAP_DICT["temperature"], bounds, "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="ERA5")
        utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_LST_{}_anoms_era5".format(settings.YEAR), cube[0], \
                                   settings.COLOURMAP_DICT["temperature"], bounds, "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", \
                                   figtext="(f) Lower Stratosphere Temperature")

    #************************************************************************
    # merra Anomaly figure
    if False:
        import netCDF4 as ncdf

        ncfile = ncdf.Dataset(settings.REANALYSISLOC +
                              "merra2_tls_ANNUAL_anom.nc")

        var = ncfile.variables["TLS ANOM"][:]  # this is a masked array
        nlons = ncfile.variables["LONGITUDES"][:]
        nlats = ncfile.variables["LATITUDES"][:]

        cube = utils.make_iris_cube_2d(var, nlats, nlons, "LST", "C")

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "LST_{}_anoms_merra".format(settings.YEAR),
            cube, settings.COLOURMAP_DICT["temperature"], bounds,
            "Anomalies from 1981-2010 (" + r'$^{\circ}$' + "C)")

    #************************************************************************
    # 2015 MERRA seasonal figure

    # import netCDF4 as ncdf

    # month_list = []

    # for month in MONTHS:
    #     print month

    #     # IRIS doesn't like the whitespace in the "TLS ANOM"
    #     ncfile=ncdf.Dataset(settings.REANALYSISLOC + "merra2_tls_{}_anom.nc".format(month.upper()),'r')

    #     var=ncfile.variables["TLS ANOM"][:] # this is a masked array
    #     lons = ncfile.variables["LONGITUDES"][:]
    #     lats = ncfile.variables["LATITUDES"][:]

    #     ncfile.close()

    #     cube = utils.make_iris_cube_2d(var, lats, lons, "TLS_ANOM", "C")

    #     month_list += [cube]

    # # pass to plotting routine
    # utils.plot_smooth_map_iris_multipanel(settings.IMAGELOC + "LST_{}_monthly_merra".format(settings.YEAR), month_list, \
    #                                           settings.COLOURMAP_DICT["temperature"], bounds, \
    #                                           "Anomaly ("+r'$^{\circ}$'+"C)", shape = (6,2), \
    #                                           title = MONTHS, \
    #                                           figtext = ["(a)","(b)","(c)","(d)", "(e)","(f)","(g)","(h)","(i)","(j)","(k)","(l)"])

    return  # run_all_plots