Exemple #1
0
def run_all_plots():

    #************************************************************************
    # Snow cover figure

    NH, Eurasia, NAmer = read_snow(
        DATALOC + "Robinson-snow-cover-{}.csv".format(settings.YEAR))

    fig = plt.figure(figsize=(8, 5))
    plt.clf()
    ax = plt.axes([0.10, 0.10, 0.86, 0.87])

    utils.plot_ts_panel(ax, [NH, Eurasia, NAmer],
                        "-",
                        "cryosphere",
                        loc=LEGEND_LOC)

    # sort formatting
    plt.xlim([1966, int(settings.YEAR) + 1])
    plt.ylim([-1.9, 3.3])
    ax.set_ylabel("Anomaly (Million km" + r'$^2$' + ")",
                  fontsize=settings.FONTSIZE)

    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)

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

    plt.close()

    return  # run_all_plots
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
Exemple #3
0
def run_all_plots():

    #************************************************************************
    # GRACE timeseries
    if True:

        #       model = read_ts(DATALOC + "glb_avg_tws_2003-2018_model.txt", "Model")
        #        model.ls = "--"
        grace = read_ts(DATALOC + "avg_JPLM06v2_land.txt", "GRACE")
        grace_fo = utils.Timeseries("GRACE FO", grace.times[:], grace.data[:])

        # post 2018
        locs, = np.where(grace_fo.times > 2018)
        grace_fo.times = grace_fo.times[locs]
        grace_fo.data = grace_fo.data[locs]

        # pre 2018
        locs, = np.where(grace.times < 2018)
        grace.times = grace.times[locs]
        grace.data = grace.data[locs]

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

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

        utils.plot_ts_panel(ax1, [grace, grace_fo],
                            "-",
                            "hydrological",
                            loc=LEGEND_LOC)

        #*******************
        # prettify
        ax1.set_ylim([-5.2, 2.3])
        ax1.set_xlim([2003, int(settings.YEAR) + 1.3])
        ax1.set_ylabel("Anomaly (cm)", 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)

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

    #************************************************************************
    # Hovmuller - Model
    if False:
        times, latitudes, data = read_hovmuller(DATALOC + "zonal_mean_tws.txt")

        bounds = np.array([-200, -12, -9, -6, -3, 0, 3, 6, 9, 12, 200])

        utils.plot_hovmuller(settings.IMAGELOC + "TWS_hovmuller_grace", times,
                             latitudes, data,
                             settings.COLOURMAP_DICT["hydrological"], bounds,
                             "Anomaly (cm)")

    #************************************************************************
    # GRACE Hovmuller
    if True:
        times, latitudes, data = read_hovmuller_2017(DATALOC)

        bounds = np.array([-200, -12, -9, -6, -3, 0, 3, 6, 9, 12, 200])

        utils.plot_hovmuller(settings.IMAGELOC + "TWS_hovmuller_grace", times,
                             latitudes, data.T,
                             settings.COLOURMAP_DICT["hydrological"], bounds,
                             "Anomaly (cm)")

    #************************************************************************
    # Difference Map
    if True:
        cube = read_map_data(
            DATALOC + "tws_changes_{}-{}_2.txt".format(settings.YEAR,
                                                       int(settings.YEAR) - 1))

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "p2.1_TWS_{}_diffs".format(settings.YEAR),
            cube,
            settings.COLOURMAP_DICT["hydrological"],
            bounds,
            "Difference between {} and {} Equivalent Depth of Water (cm)".
            format(settings.YEAR,
                   int(settings.YEAR) - 1),
            figtext="(q) Terrestrial Water Storage")

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "TWS_{}_diffs".format(settings.YEAR), cube,
            settings.COLOURMAP_DICT["hydrological"], bounds,
            "Difference between {} and {} Equivalent Depth of Water (cm)".
            format(settings.YEAR,
                   int(settings.YEAR) - 1))

    return  # run_all_plots
Exemple #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
Exemple #5
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
Exemple #6
0
def run_all_plots():

    #************************************************************************
    # Timeseries figure (2 panels)
    if True:
        for region in ["global"]:

            if region == "global":
                raobcore, rich, ratpac, UAH, rss, era5, merra, jra = \
                    read_csv(DATALOC + "SotC_AnnTemps_2020_0520_LTTGL.csv")

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

            # sondes
            utils.plot_ts_panel(ax1, [raobcore, rich, ratpac], "-", "temperature", loc=LEGEND_LOC)

            # satellites
            utils.plot_ts_panel(ax2, [UAH, rss], "-", "temperature", loc=LEGEND_LOC)

            ax2.set_ylabel("Anomaly ("+r'$^\circ$'+"C)", fontsize=settings.FONTSIZE)


            # reanalyses
            if region == "global":
    #            jra_actuals, jra_anoms = utils.read_jra55(settings.REANALYSISLOC + "JRA-55_MSUch2LT_global_ts.txt", "temperature")
    #            merra_actuals, merra_anoms = utils.read_merra_LT_LS(settings.REANALYSISLOC + "MERRA2_MSU_Tanom_ann_{}.dat".format(settings.YEAR), LT=True)
    #            utils.plot_ts_panel(ax3, [erai, era5, jra_anoms, merra_anoms], "-", "temperature", loc=LEGEND_LOC)
                twenty_cr_actuals = utils.read_20cr(settings.REANALYSISLOC + "tlt.global.txt", "temperature")
                dummy, twenty_cr_anoms = utils.calculate_climatology_and_anomalies_1d(twenty_cr_actuals, 1981, 2010)


                utils.plot_ts_panel(ax3, [era5, jra, merra], "-", "temperature", loc=LEGEND_LOC)
            else:
                utils.plot_ts_panel(ax3, [era5], "-", "temperature", loc=LEGEND_LOC)


            # sort formatting
            plt.xlim([raobcore.times[0]-1, raobcore.times[-1]+1])
            ax1.set_ylim([-0.89, 0.89])
            ax2.set_ylim([-0.89, 0.89])
            ax3.set_ylim([-0.89, 0.89])

            for tick in ax3.xaxis.get_major_ticks():
                tick.label.set_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.label.set_fontsize(settings.FONTSIZE)
            for tick in ax3.yaxis.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)
            ax3.text(0.02, 0.9, "(c) Reanalyses", transform=ax3.transAxes, fontsize=settings.LABEL_FONTSIZE)

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

            plt.savefig(settings.IMAGELOC+"LTT_ts_{}{}".format(region, settings.OUTFMT))

            plt.close()

    # #************************************************************************
    # # Land Fraction - 2018

    # high, low = read_hilo(DATALOC + "high_low.dat")
    # fig, ax1 = plt.subplots(1, figsize=(8, 5))

    # ax1.plot(high.times, high.data, c="r", ls="-", lw=2, label=high.name)
    # ax1.plot(low.times, low.data, c="b", ls="-", lw=2, label=low.name)
    
    # ax1.legend(loc="upper right", ncol=2, frameon=False, prop={'size':settings.FONTSIZE})
    # ax1.set_xlim([1978, int(settings.YEAR)+2])
    # ax1.set_ylabel("Percentage of Global Area (%)", 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)
    # utils.thicken_panel_border(ax1)

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

    # plt.close()

    #************************************************************************
    # Read in ERA5 anomalies
    if False:
        cube_list = iris.load(DATALOC + "2019TLTAnom.nc")
        names = np.array([c.var_name for c in cube_list])

        loc, = np.where(names == "tltAnnualAnom")[0]

        cube = cube_list[loc]

        bounds = np.array([-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100])
        bounds = np.array([-100, -1.6, -1.2, -0.8, -0.4, 0, 0.4, 0.8, 1.2, 1.6, 100])
        bounds = np.array([-100, -2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2.0, 100])

        cmap = settings.COLOURMAP_DICT["temperature"]
        utils.plot_smooth_map_iris(settings.IMAGELOC + "LTT_{}_anoms_era5".format(settings.YEAR), cube, cmap, \
                                       bounds, "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="ERA5")
        utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_LTT_{}_anoms_era5".format(settings.YEAR), cube, \
                                       cmap, bounds, "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", \
                                       figtext="(e) Lower Tropospheric Temperature")


    #************************************************************************
    # Read in ERA5 anomalies with record pixels
    if True:
        cube_list = iris.load(DATALOC + "2019TLTAnom_warmest.nc")
        names = np.array([c.var_name for c in cube_list])

        loc, = np.where(names == "tltAnnualAnom")[0]

        cube = cube_list[loc]

        loc, = np.where(names == "recordMask")[0]
        record = cube_list[loc]
        record.coord("latitude").guess_bounds()
        record.coord("longitude").guess_bounds()

        lats, lons, data = [], [], []
        for t, lat in enumerate(record.coord("latitude").points):
            for n, lon in enumerate(record.coord("longitude").points):
                if record.data[t, n] == 1:
                    data += [cube.data[t, n]]
                    lats += [np.mean(record.coord("latitude").bounds[t])]
                    lons += [np.mean(record.coord("longitude").bounds[n])]
        
        bounds = np.array([-100, -2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2.0, 100])

        cmap = settings.COLOURMAP_DICT["temperature"]
        utils.plot_smooth_map_iris(settings.IMAGELOC + "LTT_{}_anoms_era5".format(settings.YEAR), cube, cmap, \
                                       bounds, "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="ERA5", \
                                   scatter=(lons, lats, data), smarker="dots")
        utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_LTT_{}_anoms_era5".format(settings.YEAR), cube, \
                                       cmap, bounds, "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", \
                                       figtext="(e) Lower Tropospheric Temperature", \
                                   scatter=(lons, lats, data), smarker="dots")

    #************************************************************************
    # ERA-I Hovmuller

    # times, latitudes, data = utils.erai_2dts_read(settings.REANALYSISLOC, "ltt")

    # bounds = np.array([-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100])
    # bounds = np.array([-100, -1.6, -1.2, -0.8, -0.4, 0, 0.4, 0.8, 1.2, 1.6, 100])

    # # sort the time axis
    # start = (times[0] - 101)/10000.
    # end = (times[-1] - 1201)/10000.

    # year = start
    # new_times = []

    # months = (np.arange(12))/12.

    # while year <= end:
    #     new_times += [np.array([year for i in range(12)]) + months]
    #     year += 1

    # new_times = np.array(new_times).reshape(-1)
    # # sort the climatology to 1981-2010 (monthly!)

    # # reshape to deal with monthly
    # data = data.reshape(-1, 12, data.shape[-1])
    # new_times = new_times.reshape(-1, 12)

    # # extract climatology period
    # start_loc, = np.where(new_times[:, 0] == CLIMSTART)
    # end_loc, = np.where(new_times[:, 0] == CLIMEND)
    # clim_data = data[start_loc[0]:end_loc[0] + 1, :, :]
    # climatology = np.mean(clim_data, axis=0)

    # # make anomalies
    # data = np.array([data[i, :, :] - climatology for i in range(data.shape[0])])

    # # return to original shapes
    # data = data.reshape(-1, data.shape[-1])
    # new_times = new_times.reshape(-1)

    # utils.plot_hovmuller(settings.IMAGELOC + "LTT_hovmuller_erai", new_times, latitudes, data.T, \
    #                          settings.COLOURMAP_DICT["temperature"], bounds, \
    #                          "Anomaly ("+r'$^{\circ}$'+"C)", cosine=True)


    # version with MEI on top
    # mei = read_mei(os.path.join(DATALOC, "MEI.dat"))


    # utils.plot_hovmuller(settings.IMAGELOC + "LTT_hovmuller_era_MEI", new_times, latitudes, data.T, \
    #                          settings.COLOURMAP_DICT["temperature"], bounds, \
    #                          "Anomaly ("+r'$^{\circ}$'+"C)", cosine=True, extra_ts=mei)


    return # run_all_plots
Exemple #7
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
def run_all_plots():

    #***********************
    # MODIS - centre

    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() == "SOS":
            sos_cube = cubelist[c]

    # deal with NANS
    sos_cube.data = np.ma.masked_where(sos_cube.data != sos_cube.data,
                                       sos_cube.data)

    # read in sites

    us_locations = read_us_phenocam(os.path.join(data_loc,
                                                 "phenocam_locs.txt"))

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

    # set up plot settings
    BOUNDS = [-100, -20, -10, -5, -2, 0, 2, 5, 10, 20, 100]

    LABELS = "(c) 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)

    # axes for polar plot
    ax = plt.axes(
        [0.05, 0.01, 0.9, 0.65],
        projection=cartopy.crs.NorthPolarStereo(central_longitude=300.0))

    plot_cube = sos_cube

    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)

    cmap = settings.COLOURMAP_DICT["phenological_r"]
    norm = mpl.cm.colors.BoundaryNorm(BOUNDS, cmap.N)
    mesh = iris.plot.pcolormesh(plot_cube, cmap=cmap, norm=norm, axes=ax)

    # plot scatter
    COL = "yellow"
    ax.scatter(us_locations[1],
               us_locations[0],
               c=COL,
               s=100,
               edgecolor="k",
               transform=cartopy.crs.Geodetic(),
               zorder=10)
    ax.scatter(-2.9376,
               54.3739,
               c=COL,
               s=100,
               edgecolor="k",
               transform=cartopy.crs.Geodetic(),
               zorder=10)

    # uk box
    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,
            fontsize=settings.FONTSIZE * 0.8,
            transform=ax.transAxes)

    cb = plt.colorbar(mesh,
                      orientation='horizontal',
                      ticks=BOUNDS[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[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 sos_cube
    del cubelist

    #***********************
    # MODIS timeseries - 2018

    sos_na, sos_ea, sprt_na_orig, sprt_ea_orig = 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)

    dummy, sprt_na = utils.calculate_climatology_and_anomalies_1d(
        sprt_na_orig, 2000, 2010)
    dummy, sprt_ea = utils.calculate_climatology_and_anomalies_1d(
        sprt_ea_orig, 2000, 2010)

    ax = plt.axes([0.1, 0.7, 0.8, 0.15])
    label = "(b) North America"
    anomalies = [
        "2018 SOS Anomaly = 1.86 days",
        "2018 Spring T anomaly = -0.75 " + r'$^{\circ}$' + "C"
    ]

    plot_modis_ts(ax, sos_na, sprt_na, sprt_na_orig, label, anomalies,
                  LEGEND_LOC)

    na_trend = -0.64 / 10
    ax.plot([sos_na.times[0], sos_na.times[-1]],
            utils.trendline(na_trend, sos_na.times),
            ls="--",
            zorder=10,
            c="g",
            lw=2)
    print(utils.trendline(na_trend, sos_na.times))

    ax1 = plt.axes([0.1, 0.85, 0.8, 0.15], sharex=ax)
    label = "(a) Eurasia"
    anomalies = [
        "2018 SOS Anomaly = 2.01 days",
        "2018 Spring T anomaly = 0.13 " + r'$^{\circ}$' + "C"
    ]

    plot_modis_ts(ax1, sos_ea, sprt_ea, sprt_ea_orig, label, anomalies, "")

    ea_trend = -1.59 / 10
    ax1.plot([sos_ea.times[0], sos_ea.times[-1]],
             utils.trendline(ea_trend, sos_ea.times),
             ls="--",
             zorder=10,
             c="g",
             lw=2)
    print(utils.trendline(ea_trend, sos_ea.times))

    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.setp(ax.get_xticklabels(), visible=True)

    fig.text(0.05, 0.92, "SOS Anomaly (days)", rotation="vertical")
    fig.text(0.95,
             0.92,
             "Temperature Anomaly (" + r'$^{\circ}$' + "C)",
             rotation="vertical")

    plt.savefig(image_loc +
                "PHEN_modis_{}{}".format(settings.YEAR, settings.OUTFMT))

    #***********************
    # US timeseries - 2018

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

    barrow, ozarks, turkey = read_us_phenocam_csv(
        os.path.join(data_loc, "Richardson PhenoCam plots for Sidebar.csv"))

    ax = plt.axes([0.1, 0.03, 0.35, 0.17])
    plot_us_phenocam(ax, barrow, [160, 229], "Barrow")
    ax.text(0.05, 0.85, "(e) Barrow", transform=ax.transAxes)
    ax = plt.axes([0.1, 0.23, 0.35, 0.17])
    plot_us_phenocam(ax,
                     ozarks, [90, 159],
                     "Ozarks",
                     ylabel="Vegetation Greenness Index",
                     legend=True)
    ax.text(0.05, 0.85, "(d) Ozarks", transform=ax.transAxes)
    ax = plt.axes([0.1, 0.43, 0.35, 0.17])
    plot_us_phenocam(ax, turkey, [60, 129], "Turkey Point")
    ax.text(0.05, 0.85, "(c) Turkey Point", transform=ax.transAxes)

    ax = plt.axes([0.48, 0.02, 0.25, 0.2])
    plot_images(ax, "barrow_2017_06_27_100002.jpg")
    ax = plt.axes([0.48, 0.22, 0.25, 0.2])
    plot_images(ax, "missouriozarks_2017_04_30_163113.jpg")
    ax = plt.axes([0.48, 0.42, 0.25, 0.2])
    plot_images(ax, "turkeypointenf39_2017_04_18_113106.jpg")

    ax = plt.axes([0.73, 0.02, 0.25, 0.2])
    plot_images(ax, "barrow_2018_06_27_103003.jpg")
    ax = plt.axes([0.73, 0.22, 0.25, 0.2])
    plot_images(ax, "missouriozarks_2018_04_30_163113.jpg")
    ax = plt.axes([0.73, 0.42, 0.25, 0.2])
    plot_images(ax, "turkeypointenf39_2018_04_18_113302.jpg")

    plt.figtext(0.6, 0.02, "2017")
    plt.figtext(0.85, 0.02, "2018")

    #***********************
    # UK timeseries - 2018

    ax = plt.axes([0.1, 0.65, 0.85, 0.15])

    oak = read_uk_oak_csv(
        os.path.join(data_loc, "UK Oak budburst 2000-2018.csv"))
    utils.plot_ts_panel(ax, [oak], "-", "phenological", loc="lower left")
    ax.set_ylim([94, 124])
    ax.text(0.03, 0.8, "(b) Oak Budburst", transform=ax.transAxes)
    # fix the legend label to be italic
    handles, labels = ax.get_legend_handles_labels()
    labels[
        0] = "$\mathregular{\mathit{Quercus}}$" + " " + "$\mathregular{\mathit{robur}}$"
    ax.legend(handles, labels, frameon=False, loc="lower left")

    # need legend once have other panel's data
    north, south = read_windermere_csv(
        os.path.join(data_loc, "Windermere_2000-2018.csv"))
    ax2 = plt.axes([0.1, 0.8, 0.85, 0.15], sharex=ax)
    utils.plot_ts_panel(ax2, [north, south],
                        "-",
                        "phenological",
                        loc="lower right")
    ax2.set_ylim([79, 159])
    plt.setp(ax2.get_xticklabels(), visible=False)
    ax2.text(0.03, 0.8, "(a) Windermere", transform=ax2.transAxes)

    ax2.set_xlim([1998, 2020])
    ax.set_xlim([1998, 2020])

    fig.text(0.03, 0.835, "Day of year", rotation="vertical")

    plt.savefig(image_loc +
                "PHEN_timeseries_{}{}".format(settings.YEAR, settings.OUTFMT))
    plt.close()

    return  # run_all_plots
Exemple #9
0
def run_all_plots():

    cubelist = iris.load(
        os.path.join(DATALOC,
                     "era5_lic_anom_1979_2019_NH.nc".format(settings.YEAR)))
    names = np.array([c.name() for c in cubelist])

    LABELS = {
        "Ice Start": "(a) Ice On",
        "Ice End": "(b) Ice Off",
        "Ice Duration": "(c) Ice Duration"
    }
    COLORS = {
        "Ice Start": plt.cm.RdBu_r,
        "Ice End": plt.cm.RdBu,
        "Ice Duration": plt.cm.RdBu
    }

    BOUNDS = [-100, -20, -10, -5, -2, 0, 2, 5, 10, 20, 100]

    for name in names:
        if name == "Ice Depth":
            continue

        c, = np.where(names == name)[0]

        cube = cubelist[c]

        fig = plt.figure(figsize=(8, 9.5))
        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.98],
            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)

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

        # label axes
        ax.text(0.01,
                1.0,
                "{}".format(LABELS[name]),
                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())

        plt.savefig(settings.IMAGELOC + "LIC_map_{}_{}{}".format(
            settings.YEAR, "".join(name.split()), settings.OUTFMT))

    #************************************************************************
    # and temperatures
    BOUNDS = [-100, -4, -3, -2, -1, 0, 1, 2, 3, 4, 100]
    cubelist = iris.load(os.path.join(DATALOC, "amaps.nc"))

    cube = cubelist[0]

    fig = plt.figure(figsize=(8, 9.5))
    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.98],
        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)

    cmap = plt.cm.RdBu_r
    norm = mpl.cm.colors.BoundaryNorm(BOUNDS, cmap.N)
    mesh = iris.plot.pcolormesh(plot_cube, cmap=cmap, norm=norm, axes=ax)

    # label axes
    ax.text(0.01,
            1.0,
            "(d) Nov-Apr Air Temperature",
            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 ($^\circ$C)", 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())

    plt.savefig(
        settings.IMAGELOC +
        "LIC_map_{}_{}{}".format(settings.YEAR, "AirT", settings.OUTFMT))

    #************************************************************************
    # Timeseries
    era_start, era_end, era_length = read_column_csv(
        os.path.join(DATALOC,
                     "era5_lic_anom_1979_{}_NH.csv".format(settings.YEAR)))
    situ_start, situ_end, situ_length = read_column_csv(os.path.join(
        DATALOC, "situ_lic_anom_1979_{}_NH.csv".format(settings.YEAR)),
                                                        era=False)

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

    # start
    utils.plot_ts_panel(ax1, [era_start, situ_start],
                        "-",
                        "cryosphere",
                        loc="")

    # end
    utils.plot_ts_panel(ax2, [era_end, situ_end], "-", "cryosphere", loc="")
    ax2.set_ylabel("Anomaly (day)", fontsize=settings.FONTSIZE)

    # duration
    utils.plot_ts_panel(ax3, [era_length, situ_length],
                        "-",
                        "cryosphere",
                        loc="lower left")

    # sort formatting
    for tick in ax3.xaxis.get_major_ticks():
        tick.label.set_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.label.set_fontsize(settings.FONTSIZE)
    for tick in ax3.yaxis.get_major_ticks():
        tick.label.set_fontsize(settings.FONTSIZE)

    # sort labelling
    ax1.text(0.02,
             0.9,
             "(a) Start of Ice Cover",
             transform=ax1.transAxes,
             fontsize=settings.LABEL_FONTSIZE)
    ax2.text(0.02,
             0.9,
             "(b) End of Ice Cover",
             transform=ax2.transAxes,
             fontsize=settings.LABEL_FONTSIZE)
    ax3.text(0.02,
             0.9,
             "(c) Duration of Ice Cover",
             transform=ax3.transAxes,
             fontsize=settings.LABEL_FONTSIZE)

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

    plt.savefig(settings.IMAGELOC +
                "LIC_ts_{}{}".format(settings.YEAR, settings.OUTFMT))

    #************************************************************************
    # Timeseries
    indata = read_continuous_csv(os.path.join(DATALOC, "great_lakes_anom.csv"))

    fig = plt.figure(figsize=(8, 6))
    plt.clf()
    ax = plt.axes([0.1, 0.05, 0.88, 0.9])

    utils.plot_ts_panel(ax, indata, "-", "cryosphere", loc="")

    fig.text(0.02,
             0.5,
             "Maximum ice cover (anomaly, %)",
             va='center',
             rotation='vertical',
             ha="center",
             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)

    plt.savefig(settings.IMAGELOC +
                "LIC_GL_ts_{}{}".format(settings.YEAR, settings.OUTFMT))

    return  # run_all_plots
Exemple #10
0
def run_all_plots():

    #*********************************************
    # Timeseries plot
    if False:
        (hadisdhLQ, hadcruhLQ, hadcruhextLQ, daiLQ, eraiLQ, era5LQ, merraLQ, jraLQ, era5_mskLQ, merra_mskLQ, cr20LQ) = \
            read_ts(DATALOC + "HUM_timeseries_ALL{}.txt".format(settings.YEAR), "q", "L")
        (hadisdhMQ, hadcruhMQ, daiMQ, nocsMQ, hoapsMQ, eraiMQ, era5MQ, merraMQ, jraMQ, cr20MQ) = \
            read_ts(DATALOC + "HUM_timeseries_ALL{}.txt".format(settings.YEAR), "q", "M")
        (hadisdhLR, hadcruhLR, hadcruhextLR, daiLR, eraiLR, era5LR, merraLR, jraLR, era5_mskLR, merra_mskLR, cr20LR) = \
            read_ts(DATALOC + "HUM_timeseries_ALL{}.txt".format(settings.YEAR), "rh", "L")
        (hadisdhMR, hadcruhMR, daiMR, nocsMR, hoapsMR, eraiMR, era5MR, merraMR, jraMR, cr20MR) = \
            read_ts(DATALOC + "HUM_timeseries_ALL{}.txt".format(settings.YEAR), "rh", "M")

        COLOURS = settings.COLOURS["hydrological"]
        fig = plt.figure(figsize=(14, 12))

        # manually set up the 8 axes
        w = 0.45 # width
        h = 0.24 # height
        c = 0.53 # centre line of plots
        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)

        if int(settings.YEAR) < 2019:
            # in situ
            utils.plot_ts_panel(ax1, [hadisdhLQ, hadcruhLQ, hadcruhextLQ, daiLQ, era5_mskLQ], "-", "hydrological", loc=LEGEND_LOC, bbox=BBOX)
            utils.plot_ts_panel(ax3, [hadisdhMQ, hadcruhMQ, daiMQ, nocsMQ, hoapsMQ], "-", "hydrological", loc=LEGEND_LOC, bbox=BBOX)
            utils.plot_ts_panel(ax5, [hadisdhLR, hadcruhLR, hadcruhextLR, daiLR, era5_mskLR], "-", "hydrological", loc="")
            utils.plot_ts_panel(ax7, [hadisdhMR, hadcruhMR, daiMR], "-", "hydrological", loc="")

            # reanalyses
            utils.plot_ts_panel(ax2, [eraiLQ, era5LQ, merraLQ, jraLQ], "-", "hydrological", loc=LEGEND_LOC, bbox=BBOX)
            utils.plot_ts_panel(ax4, [eraiMQ, era5MQ, merraMQ, jraMQ], "-", "hydrological", loc=LEGEND_LOC, bbox=BBOX)
            utils.plot_ts_panel(ax6, [eraiLR, era5LR, jraLR], "-", "hydrological", loc="")
            utils.plot_ts_panel(ax8, [eraiMR, era5MR, jraMR], "-", "hydrological", loc="")
        else:
            # in situ
            utils.plot_ts_panel(ax1, [hadisdhLQ], "-", "hydrological", loc=LEGEND_LOC, bbox=BBOX)
            utils.plot_ts_panel(ax3, [hadisdhMQ, nocsMQ], "-", "hydrological", loc=LEGEND_LOC, bbox=BBOX)
            utils.plot_ts_panel(ax5, [hadisdhLR], "-", "hydrological", loc="")
            utils.plot_ts_panel(ax7, [hadisdhMR], "-", "hydrological", loc="")

            # hadisdh uncertainties in due course

            # reanalyses
            utils.plot_ts_panel(ax2, [era5LQ, merraLQ, jraLQ, cr20LQ], "-", "hydrological", loc=LEGEND_LOC, bbox=BBOX)
            utils.plot_ts_panel(ax4, [era5MQ, merraMQ, jraMQ, cr20MQ], "-", "hydrological", loc=LEGEND_LOC, bbox=BBOX)
            utils.plot_ts_panel(ax6, [era5LR, jraLR, cr20LR], "-", "hydrological", loc="")
            utils.plot_ts_panel(ax8, [era5MR, jraMR, cr20MR], "-", "hydrological", loc="")

        # prettify
        ax1.set_xlim([1957, int(settings.YEAR)+2])
        ax2.set_xlim([1957, int(settings.YEAR)+2])
        ax1.set_xticklabels(["", "1960", "1970", "1980", "1990", "2000", "2010", ""])

        for ax in [ax1, ax2, ax3, ax4]:
            ax.set_ylim([-0.39, 0.8])
        for ax in [ax5, ax6, ax7, ax8]:
            ax.set_ylim([-1.8, 1.5])

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

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


        ax1.text(0.02, 0.85, "(a) In Situ Land q", transform=ax1.transAxes, fontsize=settings.FONTSIZE)
        ax2.text(0.02, 0.85, "(b) Reanalyses Land q", transform=ax2.transAxes, fontsize=settings.FONTSIZE)
        ax3.text(0.02, 0.85, "(c) In Situ Ocean q", transform=ax3.transAxes, fontsize=settings.FONTSIZE)
        ax4.text(0.02, 0.85, "(d) Reanalyses Ocean q", transform=ax4.transAxes, fontsize=settings.FONTSIZE)
        ax5.text(0.02, 0.85, "(e) In Situ Land RH", transform=ax5.transAxes, fontsize=settings.FONTSIZE)
        ax6.text(0.02, 0.85, "(f) Reanalyses Land RH", transform=ax6.transAxes, fontsize=settings.FONTSIZE)
        ax7.text(0.02, 0.85, "(g) In Situ Ocean RH", transform=ax7.transAxes, fontsize=settings.FONTSIZE)
        ax8.text(0.02, 0.85, "(h) Reanalyses Ocean RH", transform=ax8.transAxes, fontsize=settings.FONTSIZE)


        plt.figtext(0.01, 0.75, "Specific Humidity (g kg"+r'$^{-1}$'+")", va='center', rotation='vertical', fontsize=settings.FONTSIZE)
        plt.figtext(0.01, 0.25, "Relative Humidity (%rh)", va='center', rotation='vertical', fontsize=settings.FONTSIZE)

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

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

    #*********************************************
    # Timeseries uncertainty plot
    if True:
        (hadisdhLQ, hadisdhLQ_l, hadisdhLQ_u, era5LQ, merraLQ, jraLQ, era5_mskLQ, merra_mskLQ, cr20LQ) = \
            read_ts_unc(DATALOC + "HUM_timeseries_ALL{}_unc.txt".format(settings.YEAR), "q", "L")
        (hadisdhMQ, hadisdhMQ_l, hadisdhMQ_u, nocsMQ, era5MQ, merraMQ, jraMQ, cr20MQ) = \
            read_ts_unc(DATALOC + "HUM_timeseries_ALL{}_unc.txt".format(settings.YEAR), "q", "M")
        (hadisdhLR, hadisdhLR_l, hadisdhLR_u,  era5LR, merraLR, jraLR, era5_mskLR, merra_mskLR, cr20LR) = \
            read_ts_unc(DATALOC + "HUM_timeseries_ALL{}_unc.txt".format(settings.YEAR), "rh", "L")
        (hadisdhMR, hadisdhMR_l, hadisdhMR_u, nocsMR, era5MR, merraMR, jraMR, cr20MR) = \
            read_ts_unc(DATALOC + "HUM_timeseries_ALL{}_unc.txt".format(settings.YEAR), "rh", "M")

        COLOURS = settings.COLOURS["hydrological"]
        fig = plt.figure(figsize=(14, 12))

        # manually set up the 8 axes
        w = 0.45 # width
        h = 0.24 # height
        c = 0.53 # centre line of plots
        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)

        # in situ
        utils.plot_ts_panel(ax1, [hadisdhLQ], "-", "hydrological", loc="",)
        ax1.fill_between(hadisdhLQ.times, hadisdhLQ_u.data, hadisdhLQ_l.data, color='0.8', label="")
        utils.plot_ts_panel(ax3, [hadisdhMQ, nocsMQ], "-", "hydrological", loc="")
        ax3.fill_between(hadisdhMQ.times, hadisdhMQ_u.data, hadisdhMQ_l.data, color='0.8', label="")
        utils.plot_ts_panel(ax5, [hadisdhLR], "-", "hydrological", loc="")
        ax5.fill_between(hadisdhLR.times, hadisdhLR_u.data, hadisdhLR_l.data, color='0.8', label="")
        utils.plot_ts_panel(ax7, [hadisdhMR], "-", "hydrological", loc="")
        ax7.fill_between(hadisdhMR.times, hadisdhMR_u.data, hadisdhMR_l.data, color='0.8', label="")

    
        # reanalyses
        utils.plot_ts_panel(ax2, [era5LQ, merraLQ, jraLQ, cr20LQ], "-", "hydrological", loc=LEGEND_LOC, bbox=BBOX)
        utils.plot_ts_panel(ax4, [era5MQ, merraMQ, jraMQ, cr20MQ], "-", "hydrological", loc=LEGEND_LOC, bbox=BBOX)
        utils.plot_ts_panel(ax6, [era5LR, jraLR, cr20LR], "-", "hydrological", loc="")
        utils.plot_ts_panel(ax8, [era5MR, jraMR, cr20MR], "-", "hydrological", loc="")

        # fix legend
        unc_patch = ax1.fill(np.NaN, np.NaN, '0.8', zorder = 1, alpha=0.7)

        for ax in [ax1, ax3]:
            lines = []
            labels = []
            for line in ax.get_lines():
                if line.get_label() == "HadISDH":
                    lines += [(line, unc_patch[0])]
                    labels += [line.get_label()]                   
                else:
                    lines += [line]
                    labels += [line.get_label()]


            ax.legend(lines, labels, \
                       loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
                       labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=BBOX)

        # prettify
        ax1.set_xlim([1957, int(settings.YEAR)+2])
        ax2.set_xlim([1957, int(settings.YEAR)+2])
        ax1.set_xticklabels(["", "1960", "1970", "1980", "1990", "2000", "2010", ""])

        for ax in [ax1, ax2, ax3, ax4]:
            ax.set_ylim([-0.39, 0.8])
        for ax in [ax5, ax6, ax7, ax8]:
            ax.set_ylim([-1.8, 1.5])

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

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


        ax1.text(0.02, 0.85, "(a) In Situ Land q", transform=ax1.transAxes, fontsize=settings.FONTSIZE)
        ax2.text(0.02, 0.85, "(b) Reanalyses Land q", transform=ax2.transAxes, fontsize=settings.FONTSIZE)
        ax3.text(0.02, 0.85, "(c) In Situ Ocean q", transform=ax3.transAxes, fontsize=settings.FONTSIZE)
        ax4.text(0.02, 0.85, "(d) Reanalyses Ocean q", transform=ax4.transAxes, fontsize=settings.FONTSIZE)
        ax5.text(0.02, 0.85, "(e) In Situ Land RH", transform=ax5.transAxes, fontsize=settings.FONTSIZE)
        ax6.text(0.02, 0.85, "(f) Reanalyses Land RH", transform=ax6.transAxes, fontsize=settings.FONTSIZE)
        ax7.text(0.02, 0.85, "(g) In Situ Ocean RH", transform=ax7.transAxes, fontsize=settings.FONTSIZE)
        ax8.text(0.02, 0.85, "(h) Reanalyses Ocean RH", transform=ax8.transAxes, fontsize=settings.FONTSIZE)


        plt.figtext(0.01, 0.75, "Specific Humidity (g kg"+r'$^{-1}$'+")", va='center', rotation='vertical', fontsize=settings.FONTSIZE)
        plt.figtext(0.01, 0.25, "Relative Humidity (%rh)", va='center', rotation='vertical', fontsize=settings.FONTSIZE)

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

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

    input("stOP")
    #*********************************************
    # Map plots
    ## RH
    bounds = [-50, -12, -9, -6, -3, 0, 3, 6, 9, 12, 50]
    # RH HadISDH
    if False:
        cube = read_maps(DATALOC + "HUMrh_anomalymap_HADISDHland{}.txt".format(settings.YEAR), "HadISDH RH", None, footer=True)

        utils.plot_smooth_map_iris(settings.IMAGELOC + "HUM_RH_hadisdh_land", cube, settings.COLOURMAP_DICT["hydrological"], \
                                       bounds, "Anomalies from 1981-2010 (%rh)", figtext="", title="")

    # RH HadISDH Land and Marine
    if True:
   
        cube = read_maps(DATALOC + "HUMrh_anomalymap_HADISDH{}.txt".format(settings.YEAR), "HadISDH RH", None, footer=True)

        utils.plot_smooth_map_iris(settings.IMAGELOC + "HUM_RH_hadisdh_combined", cube, settings.COLOURMAP_DICT["hydrological"], \
                                   bounds, "Anomalies from 1981-2010 (%rh)", figtext="", title="")
        utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_HUM_RH_hadisdh_combined", cube, settings.COLOURMAP_DICT["hydrological"], \
                                   bounds, "Anomalies from 1981-2010 (%rh)", figtext="(h) Surface Relative Humidity", title="")

    # RH ERA 
    if True:
        cube = read_maps(DATALOC + "HUMrh_anomalymap_ERA5{}.txt".format(settings.YEAR), "ERA-I RH", None, footer=True)
        
        utils.plot_smooth_map_iris(settings.IMAGELOC + "HUM_RH_era5", cube, settings.COLOURMAP_DICT["hydrological"], \
                                   bounds, "Anomalies from 1981-2010 (%rh)", figtext="", title="")
        #    utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_HUM_RH_era5", cube, settings.COLOURMAP_DICT["hydrological"], \
            #                                   bounds, "Anomalies from 1981-2010 (%rh)", figtext="(o) Surface Relative Humidity", title="")

    # RH MERRA 
    if True:
        cube = read_maps(DATALOC + "HUMrh_anomalymap_MERRA2{}.txt".format(settings.YEAR), "MERRA2 RH", None, footer=True)
   
        utils.plot_smooth_map_iris(settings.IMAGELOC + "HUM_RH_merra", cube, settings.COLOURMAP_DICT["hydrological"], \
                                   bounds, "Anomalies from 1981-2010 (%rh)", figtext="", title="")

    ## Q
    bounds = [-20., -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 20]
    # q HadISDH
    if False:
        cube = read_maps(DATALOC + "HUMq_anomalymap_HADISDHland{}.txt".format(settings.YEAR), "HadISDH q", "g/kg", footer=True)

        utils.plot_smooth_map_iris(settings.IMAGELOC + "HUM_q_hadisdh_land", cube, settings.COLOURMAP_DICT["hydrological"], \
                                   bounds, "Anomalies from 1981-2010 (g kg"+r'$^{-1}$'+")", figtext="", title="")
        #    utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_HUM_q_hadisdh_land", cube, settings.COLOURMAP_DICT["hydrological"], \
            #                                   bounds, "Anomalies from 1981-2010 (g kg"+r'$^{-1}$'+")", figtext="(n) Surface Specific Humidity", title="")

    # q HadISDH Land and Marine
    if True:
        cube = read_maps(DATALOC + "HUMq_anomalymap_HADISDH{}.txt".format(settings.YEAR), "HadISDH q", "g/kg", footer=True)

        utils.plot_smooth_map_iris(settings.IMAGELOC + "HUM_q_hadisdh_combined", cube, settings.COLOURMAP_DICT["hydrological"], \
                                   bounds, "Anomalies from 1981-2010 (g kg"+r'$^{-1}$'+")", figtext="", title="")
        utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_HUM_q_hadisdh_combined", cube, settings.COLOURMAP_DICT["hydrological"], \
                                   bounds, "Anomalies from 1981-2010 (g kg"+r'$^{-1}$'+")", figtext="(g) Surface Specific Humidity", title="")

    # q ERA
    if True:
        cube = read_maps(DATALOC + "HUMq_anomalymap_ERA5{}.txt".format(settings.YEAR), "ERA-I q", "g/kg", footer=True)

        utils.plot_smooth_map_iris(settings.IMAGELOC + "HUM_q_era5", cube, settings.COLOURMAP_DICT["hydrological"], \
                                   bounds, "Anomalies from 1981-2010 (g kg"+r'$^{-1}$'+")", figtext="", title="")

    # MERRA?
    if True:
        cube = read_maps(DATALOC + "HUMq_anomalymap_MERRA2{}.txt".format(settings.YEAR), "MERRA2 q", "g/kg", footer=True)

        utils.plot_smooth_map_iris(settings.IMAGELOC + "HUM_q_merra", cube, settings.COLOURMAP_DICT["hydrological"], \
                                   bounds, "Anomalies from 1981-2010 (g kg"+r'$^{-1}$'+")", figtext="", title="")



    return # run_all_plots
Exemple #11
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
Exemple #12
0
def run_all_plots():

    if True:
        for index in INDICES:

            # dummy so far
            #        NYEARS = 66
            #        rank_bounds = [-1,1,2,3,NYEARS-2,NYEARS-1,NYEARS,100]
            rank_bounds = [-4.5, -3.5, -2.5, -1.5, 1.5, 2.5, 3.5, 4.5]

            # sort the bounds and colourbars
            if index in ["TX90p", "TN90p"]:
                bounds = [-100, -40, -30, -20, -10, 0, 10, 20, 30, 40, 100]
                cmap = settings.COLOURMAP_DICT["temperature"]
            elif index in ["TX10p", "TN10p"]:
                bounds = [-100, -40, -30, -20, -10, 0, 10, 20, 30, 40, 100]
                cmap = settings.COLOURMAP_DICT["temperature_r"]
            elif index in ["TXx", "TNx", "TXn", "TNn"]:
                bounds = [-100, -6, -4, -2, -1, 0, 1, 2, 4, 6, 100]
                cmap = settings.COLOURMAP_DICT["temperature"]

            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")[0]

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

            if index in ["TX90p", "TN90p", "TX10p", "TN10p"]:
                # change from % to days
                cube.data = cube.data * 3.65

            cube = ApplyClimatology(cube)

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

            utils.plot_smooth_map_iris(
                settings.IMAGELOC +
                "TEX_{}_{}_anoms_ghcndex".format(index, settings.YEAR),
                cube[loc[0]],
                cmap,
                bounds,
                "Anomalies from 1961-90 ({})".format(INDEX_UNITS[index]),
                title="{} - {}".format(index, INDEX_LABELS[index]),
                figtext=FIGURE_LABELS[index])

            if index == "TX90p":
                utils.plot_smooth_map_iris(
                    settings.IMAGELOC + "p2.1_TEX_{}_{}_anoms_ghcndex".format(
                        index, settings.YEAR),
                    cube[loc[0]],
                    cmap,
                    bounds,
                    "Anomalies from 1961-90 ({})".format(INDEX_UNITS[index]),
                    title="",
                    figtext="(c) Warm Days",
                    save_netcdf_filename="{}{}_for_NOAA_{}.nc".format(
                        DATALOC, index,
                        dt.datetime.strftime(dt.datetime.now(), "%d-%b-%Y")))
            if index == "TN10p":
                utils.plot_smooth_map_iris(
                    settings.IMAGELOC + "p2.1_TEX_{}_{}_anoms_ghcndex".format(
                        index, settings.YEAR),
                    cube[loc[0]],
                    cmap,
                    bounds,
                    "Anomalies from 1961-90 ({})".format(INDEX_UNITS[index]),
                    title="",
                    figtext="(d) Cool Nights",
                    save_netcdf_filename="{}{}_for_NOAA_{}.nc".format(
                        DATALOC, index,
                        dt.datetime.strftime(dt.datetime.now(), "%d-%b-%Y")))

            rank_cube = get_ranks(cube)

            plot_rank_map(
                settings.IMAGELOC +
                "TEX_{}_{}_rank_ghcndex".format(index, settings.YEAR),
                rank_cube[loc[0]],
                cmap,
                rank_bounds,
                "Rank",
                title="{} - {}".format(index, INDEX_LABELS[index]))

            #*************
            # plot season maps (2x2)

            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)[0]
                    cube = cube_list[selected_cube]

                    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'

                    if index in ["TX90p", "TN90p", "TX10p", "TN10p"]:
                        # change from % to days
                        cube.data = cube.data * (
                            3.65 / 4.)  # assume a season is 1/4 of a year

                    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
                if index in ["TX90p", "TN90p", "TX10p", "TN10p"]:
                    season_cube.data = np.ma.mean(month_data, axis=0)
                elif index in ["TXx", "TNx"]:
                    season_cube.data = np.ma.max(month_data, axis=0)
                elif index in ["TXn", "TNn"]:
                    season_cube.data = np.ma.min(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
                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 index in ["TX90p", "TN90p"]:
                bounds = [-100, -10, -7.5, -5, -2.5, 0, 2.5, 5, 7.5, 10, 100]
            elif index in ["TX10p", "TN10p"]:
                bounds = [-100, -10, -7.5, -5, -2.5, 0, 2.5, 5, 7.5, 10, 100]
            elif index in ["TXx", "TNx", "TXn", "TNn"]:
                bounds = [-100, -6, -4, -2, -1, 0, 1, 2, 4, 6, 100]

            # pass to plotting routine
            utils.plot_smooth_map_iris_multipanel(
                settings.IMAGELOC +
                "TEX_{}_{}_seasons_ghcndex".format(index, settings.YEAR),
                season_list,
                cmap,
                bounds,
                "Anomalies from 1961-90 ({})".format(INDEX_UNITS[index]),
                shape=(2, 2),
                title=SEASONS,
                figtext=SEASON_LABELS[index],
                figtitle="{} - {}".format(index, INDEX_LABELS[index]))

    #*************
    # timeseries obs
    if True:
        for index_pair in [["TX90p", "TN10p"], ["TN90p", "TX10p"]]:

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

            ax3 = ax1.twinx()
            ax4 = ax2.twinx()

            axes = (ax1, ax2, ax3, ax4)

            for ix, index in enumerate(index_pair):

                index_ts, cover_ts = obtain_timeseries(
                    DATALOC +
                    "GHCND_{}_1951-{}_RegularGrid_global_2.5x2.5deg_LSmask.nc".
                    format(index,
                           int(settings.YEAR) + 1), "Ann", "GHCNDEX", index)

                utils.plot_ts_panel(axes[ix], [index_ts],
                                    "-",
                                    "temperature",
                                    loc="",
                                    bbox=BBOX)  # no legend as single line
                axes[ix].text(0.02,
                              0.9,
                              "({}) {}".format(string.ascii_lowercase[ix],
                                               index),
                              transform=axes[ix].transAxes,
                              fontsize=settings.FONTSIZE)

                # red tickmarks
                axes[ix].tick_params(axis='y', colors='red', direction="in")

                # and smoothed
                index_ts.data.fill_value = -99.9
                smoothed = binomialfilter(index_ts.data.filled(),
                                          -99.9,
                                          5,
                                          pad=False)
                smoothed = np.ma.masked_where(smoothed == -99.9, smoothed)

                axes[ix].plot(index_ts.times, smoothed, "r--", lw=LW)

                # print the index, the current anomaly and the rank information
                print(index,
                      index_ts.data.compressed()[-1] / 36.5,
                      np.argsort(np.argsort(index_ts.data.compressed())) + 1)

                axes[ix + 2].plot(cover_ts.times, cover_ts.data, "k:", lw=2)
                axes[ix + 2].yaxis.set_label_position("right")
                axes[ix + 2].yaxis.set_ticks_position('right')

            # prettify
            plt.xlim([1950, int(settings.YEAR) + 1])
            axes[0].set_ylim([15, None])
            if "X" in index:
                axes[1].set_ylim([19, 59])
            elif "N" in index:
                axes[1].set_ylim([11, 59])

            ax3.set_ylim([0, 98])
            ax4.set_ylim([0, 98])

            fig.text(0.03,
                     0.5,
                     "Number of Days",
                     va='center',
                     rotation='vertical',
                     fontsize=settings.FONTSIZE,
                     color="r")
            fig.text(0.97,
                     0.5,
                     "% land covered",
                     va='center',
                     rotation='vertical',
                     fontsize=settings.FONTSIZE)

            for ax in axes:
                for tick in ax.yaxis.get_major_ticks():
                    tick.label.set_fontsize(settings.FONTSIZE)
                    tick.label2.set_fontsize(settings.FONTSIZE)
            for tick in axes[1].xaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

            fig.subplots_adjust(left=0.1,
                                right=0.9,
                                top=0.98,
                                bottom=0.05,
                                hspace=0.001)

            plt.savefig(settings.IMAGELOC + "TEX_{}+{}_ts_ghcndex{}".format(
                index_pair[0], index_pair[1], settings.OUTFMT))
            plt.close()

    # #*************
    # # timeseries ERA-Int

    # for index_pair in [["TX90p", "TN10p"], ["TN90p", "TX10p"]]:

    #     fig, axes = plt.subplots(2, figsize=(8, 6.5), sharex=True)

    #     for ix, index in enumerate(index_pair):

    #         index_ts, cover_ts = obtain_timeseries(DATALOC + "ERA-Int_1979-{}_{}_LSmask.nc".format(settings.YEAR, index), "Annual", "ERA-Interim", index)

    #         utils.plot_ts_panel(axes[ix], [index_ts], "-", "temperature", loc = LEGEND_LOC, bbox = BBOX)

    #         axes[ix].text(0.02, 0.9, "({}) {}".format(string.ascii_lowercase[ix], index), transform = axes[ix].transAxes, fontsize = settings.FONTSIZE)

    #         # and smoothed
    #         index_ts.data.fill_value = -99.9
    #         smoothed = binomialfilter(index_ts.data.filled(), -99.9, 5, pad = False)
    #         smoothed = np.ma.masked_where(smoothed == -99.9, smoothed)

    #         axes[ix].plot(index_ts.times, smoothed, "r--", lw = LW)

    #     # prettify
    #     plt.xlim([1950,2019])
    #     axes[0].set_ylim([15,None])
    #     axes[1].set_ylim([16,59])

    #     fig.text(0.03, 0.5, "Number of Days", va='center', rotation='vertical', fontsize = settings.FONTSIZE)

    #     for ax in axes:
    #         for tick in ax.yaxis.get_major_ticks():
    #             tick.label.set_fontsize(settings.FONTSIZE)
    #     for tick in axes[1].xaxis.get_major_ticks():
    #         tick.label.set_fontsize(settings.FONTSIZE)

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

    #     plt.savefig(settings.IMAGELOC+"TEX_{}+{}_ts_erai{}".format(index_pair[0], index_pair[1], settings.OUTFMT))
    #     plt.close()

    # #*************
    # # ERA-Int Maps (annual only)

    # for index in INDICES:

    #     # sort the bounds and colourbars
    #     if index in ["TX90p", "TN90p"]:
    #         bounds = [-100, -30, -20, -10, -5, 0, 5, 10, 20, 30, 100]
    #         cmap=settings.COLOURMAP_DICT["temperature"]
    #     elif index in ["TX10p", "TN10p"]:
    #         bounds = [-100, -30, -20, -10, -5, 0, 5, 10, 20, 30, 100]
    #         cmap=settings.COLOURMAP_DICT["temperature_r"]
    #     elif index in ["TXx", "TNx", "TXn", "TNn"]:
    #         bounds = [-100, -6, -4, -2, -1, 0, 1, 2, 4, 6, 100]
    #         cmap=settings.COLOURMAP_DICT["temperature"]

    #     cube_list = iris.load(DATALOC + "ERA-Int_1979-{}_{}_LSmask.nc".format(settings.YEAR, index))
    #     names = np.array([cube.name() for cube in cube_list])

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

    #     selected_cube, = np.where(names == "Annual")[0]

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

    #     if index in ["TX90p", "TN90p", "TX10p", "TN10p"]:
    #         # change from % to days
    #         cube.data = cube.data * 3.65

    #     cube = ApplyClimatology(cube)

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

    #     utils.plot_smooth_map_iris(settings.IMAGELOC + "TEX_{}_{}_anoms_erai".format(index, settings.YEAR), cube[loc[0]], cmap, bounds, "Anomalies from 1981-2010 ({})".format(INDEX_UNITS[index]), title = "ERA-Interim {} - {}".format(index, INDEX_LABELS[index]), figtext = FIGURE_LABELS[index])

    #     #*************
    #     # plot season maps (2x2)

    #     season_list = []
    #     for season in SEASONS:

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

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

    #             if month  == "December":
    #                 # 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'

    #             if index in ["TX90p", "TN90p", "TX10p", "TN10p"]:
    #                 # change from % to days
    #                 cube.data = cube.data * (3.65/4.) # assume a season is 1/4 of a year

    #             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
    #         if index in ["TX90p", "TN90p", "TX10p", "TN10p"]:
    #             season_cube.data = np.ma.mean(month_data, axis = 0)
    #         elif index in ["TXx", "TNx"]:
    #             season_cube.data = np.ma.max(month_data, axis = 0)
    #         elif index in ["TXn", "TNn"]:
    #             season_cube.data = np.ma.min(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
    #         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 index in ["TX90p", "TN90p"]:
    #         bounds = [-100, -10, -7.5, -5, -2.5, 0, 2.5, 5, 7.5, 10, 100]
    #     elif index in ["TX10p", "TN10p"]:
    #         bounds = [-100, -10, -7.5, -5, -2.5, 0, 2.5, 5, 7.5, 10, 100]
    #     elif index in ["TXx", "TNx", "TXn", "TNn"]:
    #         bounds = [-100, -6, -4, -2, -1, 0, 1, 2, 4, 6, 100]

    #     # pass to plotting routine
    #     utils.plot_smooth_map_iris_multipanel(settings.IMAGELOC + "TEX_{}_{}_seasons_erai".format(index, settings.YEAR), season_list, cmap, bounds, "Anomalies from 1981-2010 ({})".format(INDEX_UNITS[index]), shape = (2,2), title = SEASONS, figtext = SEASON_LABELS[index], figtitle = "{} - {}".format(index, INDEX_LABELS[index]))

    #*************
    # timeseries ERA5
    ERA5LOCTEMP = "/data/users/rdunn/reanalyses/data/era5/v20200409/indices/"
    #    ERA5LOCTEMP = "/scratch/rdunn/reanalyses/era5/final/"
    if True:

        for index_pair in [["TX90p", "TN10p"], ["TN90p", "TX10p"]]:

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

            for ix, index in enumerate(index_pair):

                index_ts, cover_ts = obtain_timeseries(
                    ERA5LOCTEMP +
                    "ERA5_{}_1979-{}.nc".format(index, settings.YEAR),
                    "Ann",
                    "ERA5",
                    index,
                    is_era5=True)

                utils.plot_ts_panel(axes[ix], [index_ts],
                                    "-",
                                    "temperature",
                                    loc=LEGEND_LOC,
                                    bbox=BBOX)

                axes[ix].text(0.02,
                              0.9,
                              "({}) {}".format(string.ascii_lowercase[ix],
                                               index),
                              transform=axes[ix].transAxes,
                              fontsize=settings.FONTSIZE)

                # and smoothed
                index_ts.data.fill_value = -99.9
                smoothed = binomialfilter(index_ts.data.filled(),
                                          -99.9,
                                          5,
                                          pad=False)
                smoothed = np.ma.masked_where(smoothed == -99.9, smoothed)

                axes[ix].plot(index_ts.times, smoothed, "r--", lw=LW)

            # prettify
            plt.xlim([1950, int(settings.YEAR) + 1])
            axes[0].set_ylim([15, None])
            axes[1].set_ylim([16, 59])

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

            for ax in axes:
                for tick in ax.yaxis.get_major_ticks():
                    tick.label.set_fontsize(settings.FONTSIZE)
            for tick in axes[1].xaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

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

            plt.savefig(settings.IMAGELOC + "TEX_{}+{}_ts_era5{}".format(
                index_pair[0], index_pair[1], settings.OUTFMT))
            plt.close()

    #*************
    # ERA Maps (annual only)
    if True:
        for index in INDICES:

            # sort the bounds and colourbars
            if index in ["TX90p", "TN90p"]:
                #                bounds = [-100, -30, -20, -10, -5, 0, 5, 10, 20, 30, 100]
                bounds = [-100, -40, -30, -20, -10, 0, 10, 20, 30, 40, 100]
                cmap = settings.COLOURMAP_DICT["temperature"]
            elif index in ["TX10p", "TN10p"]:
                #                bounds = [-100, -30, -20, -10, -5, 0, 5, 10, 20, 30, 100]
                bounds = [-100, -40, -30, -20, -10, 0, 10, 20, 30, 40, 100]
                cmap = settings.COLOURMAP_DICT["temperature_r"]
            elif index in ["TXx", "TNx", "TXn", "TNn"]:
                bounds = [-100, -6, -4, -2, -1, 0, 1, 2, 4, 6, 100]
                cmap = settings.COLOURMAP_DICT["temperature"]

            cube_list = iris.load(
                ERA5LOCTEMP +
                "ERA5_{}_1979-{}.nc".format(index, settings.YEAR))
            names = np.array([cube.var_name for cube in cube_list])

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

            selected_cube, = np.where(names == "Ann")[0]

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

            if index in ["TX90p", "TN90p", "TX10p", "TN10p"]:
                # change from % to days
                cube.data = cube.data * 3.65

            cube = ApplyClimatology(cube, is_era5=True)

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

            utils.plot_smooth_map_iris(
                settings.IMAGELOC +
                "TEX_{}_{}_anoms_era5".format(index, settings.YEAR),
                cube[loc[0]],
                cmap,
                bounds,
                "Anomalies from 1981-2010 ({})".format(INDEX_UNITS[index]),
                title="ERA5 {} - {}".format(index, INDEX_LABELS[index]),
                figtext=FIGURE_LABELS[index])

            #*************
            # plot season maps (2x2)

            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)[0]
                    cube = cube_list[selected_cube]

                    if month == "December":
                        # 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'

                    if index in ["TX90p", "TN90p", "TX10p", "TN10p"]:
                        # change from % to days
                        cube.data = cube.data * (
                            3.65 / 4.)  # assume a season is 1/4 of a year

                    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
                if index in ["TX90p", "TN90p", "TX10p", "TN10p"]:
                    season_cube.data = np.ma.mean(month_data, axis=0)
                elif index in ["TXx", "TNx"]:
                    season_cube.data = np.ma.max(month_data, axis=0)
                elif index in ["TXn", "TNn"]:
                    season_cube.data = np.ma.min(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
                season_cube = ApplyClimatology(season_cube, is_era5=True)

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

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

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

            # sort the bounds and colourbars
            if index in ["TX90p", "TN90p"]:
                bounds = [-100, -10, -7.5, -5, -2.5, 0, 2.5, 5, 7.5, 10, 100]
            elif index in ["TX10p", "TN10p"]:
                bounds = [-100, -10, -7.5, -5, -2.5, 0, 2.5, 5, 7.5, 10, 100]
            elif index in ["TXx", "TNx", "TXn", "TNn"]:
                bounds = [-100, -6, -4, -2, -1, 0, 1, 2, 4, 6, 100]

            # pass to plotting routine
            utils.plot_smooth_map_iris_multipanel(
                settings.IMAGELOC +
                "TEX_{}_{}_seasons_era5".format(index, settings.YEAR),
                season_list,
                cmap,
                bounds,
                "Anomalies from 1981-2010 ({})".format(INDEX_UNITS[index]),
                shape=(2, 2),
                title=SEASONS,
                figtext=SEASON_LABELS[index],
                figtitle="ERA5 {} - {}".format(index, INDEX_LABELS[index]))

    #*************
    # timeseries obs with uncertainties
    if True:
        for index_pair in [["TX90p", "TN10p"], ["TN90p", "TX10p"]]:

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

            ax3 = ax1.twinx()
            ax4 = ax2.twinx()

            axes = (ax1, ax2, ax3, ax4)

            for ix, index in enumerate(index_pair):

                index_ts, cover_ts = obtain_timeseries(
                    DATALOC +
                    "GHCND_{}_1951-{}_RegularGrid_global_2.5x2.5deg_LSmask.nc".
                    format(index,
                           int(settings.YEAR) + 1), "Ann", "GHCNDEX", index)

                utils.plot_ts_panel(axes[ix], [index_ts],
                                    "-",
                                    "temperature",
                                    loc="",
                                    bbox=BBOX)  # no legend as single line
                axes[ix].text(0.02,
                              0.9,
                              "({}) {}".format(string.ascii_lowercase[ix],
                                               index),
                              transform=axes[ix].transAxes,
                              fontsize=settings.FONTSIZE)

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

                ghcndex_cube = cube_list[selected_cube]
                ghcndex_cube.coord('latitude').guess_bounds()
                ghcndex_cube.coord('longitude').guess_bounds()
                ghcndex_cube = fix_time_coord(ghcndex_cube)

                if index in ["TX90p", "TN90p", "TX10p", "TN10p"]:
                    # change from % to days
                    ghcndex_cube.data = ghcndex_cube.data * 3.65

                # era5 cube
                cube_list = iris.load(
                    ERA5LOCTEMP +
                    "ERA5_{}_1979-{}.nc".format(index, settings.YEAR))
                names = np.array([cube.var_name for cube in cube_list])
                selected_cube, = np.where(names == "Ann")[0]

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

                if index in ["TX90p", "TN90p", "TX10p", "TN10p"]:
                    # change from % to days
                    era5_cube.data = era5_cube.data * 3.65

                # need to regrid
                era5_cube = era5_cube.regrid(
                    ghcndex_cube,
                    iris.analysis.Linear(extrapolation_mode="mask"))

                coverage_offset, coverage_stdev = compute_coverage_error(
                    ghcndex_cube, era5_cube)
                coverage_stdev *= 2.  # 90%, 2s.d.
                axes[ix].fill_between(index_ts.times,
                                      index_ts.data - coverage_stdev,
                                      index_ts.data + coverage_stdev,
                                      color='mistyrose',
                                      label="ERA5 coverage uncertainty")

                # red tickmarks
                axes[ix].tick_params(axis='y', colors='red', direction="in")

                # and smoothed
                index_ts.data.fill_value = -99.9
                smoothed = binomialfilter(index_ts.data.filled(),
                                          -99.9,
                                          5,
                                          pad=False)
                smoothed = np.ma.masked_where(smoothed == -99.9, smoothed)

                axes[ix].plot(index_ts.times, smoothed, "r--", lw=LW)

                # print the index, the current anomaly and the rank information
                print(index,
                      index_ts.data.compressed()[-1] / 36.5,
                      np.argsort(np.argsort(index_ts.data.compressed())) + 1)

                axes[ix + 2].plot(cover_ts.times, cover_ts.data, "k:", lw=2)
                axes[ix + 2].yaxis.set_label_position("right")
                axes[ix + 2].yaxis.set_ticks_position('right')

            # prettify
            plt.xlim([1950, int(settings.YEAR) + 1])
            axes[0].set_ylim([15, None])
            if "X" in index:
                axes[1].set_ylim([19, 59])
            elif "N" in index:
                axes[1].set_ylim([11, 59])

            ax3.set_ylim([0, 98])
            ax4.set_ylim([0, 98])

            fig.text(0.03,
                     0.5,
                     "Number of Days",
                     va='center',
                     rotation='vertical',
                     fontsize=settings.FONTSIZE,
                     color="r")
            fig.text(0.97,
                     0.5,
                     "% land covered",
                     va='center',
                     rotation='vertical',
                     fontsize=settings.FONTSIZE)

            for ax in axes:
                for tick in ax.yaxis.get_major_ticks():
                    tick.label.set_fontsize(settings.FONTSIZE)
                    tick.label2.set_fontsize(settings.FONTSIZE)
            for tick in axes[1].xaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

            fig.subplots_adjust(left=0.1,
                                right=0.9,
                                top=0.98,
                                bottom=0.05,
                                hspace=0.001)

            plt.savefig(settings.IMAGELOC +
                        "TEX_{}+{}_ts_ghcndex_uncertainties{}".format(
                            index_pair[0], index_pair[1], settings.OUTFMT))
            plt.close()

    return  # run_all_plots
Exemple #13
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
Exemple #14
0
def run_all_plots():

    #************************************************************************
    # Timeseries - 2016 version
    if False:
        fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6.5), sharex=True)

        gfed = read_csv(DATALOC + "timeseries_NAme", "GFED3.1")
        gfas3 = read_csv(DATALOC + "timeseries_NAme", "GFAS1p3")
        gfas0 = read_csv(DATALOC + "timeseries_NAme", "GFAS1p0")

        utils.plot_ts_panel(ax1, [gfed, gfas3, gfas0],
                            "-",
                            "land_surface",
                            loc=LEGEND_LOC)

        ax1.set_ylabel("Tg(C) per month", fontsize=settings.FONTSIZE)
        ax1.set_ylim([0, 100])

        gfed = read_csv(DATALOC + "timeseries_TAsi", "GFED3.1")
        gfas3 = read_csv(DATALOC + "timeseries_TAsi", "GFAS1p3")
        gfas0 = read_csv(DATALOC + "timeseries_TAsi", "GFAS1p0")

        utils.plot_ts_panel(ax2, [gfed, gfas3, gfas0],
                            "-",
                            "land_surface",
                            loc=LEGEND_LOC)

        ax2.set_ylabel("Tg(C) per month", fontsize=settings.FONTSIZE)
        ax2.set_ylim([0, 450])

        # sort formatting
        plt.xlim([1997, 2017])

        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) North America",
                 transform=ax1.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax2.text(0.02,
                 0.9,
                 "(b) Tropical Asia",
                 transform=ax2.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)

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

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

        plt.close()

    #************************************************************************
    # Timeseries - 2017, 2018 version
    if True:
        fig = plt.figure(figsize=(8, 5))
        plt.clf()
        ax = plt.axes([0.11, 0.09, 0.88, 0.89])

        gfed = read_gfed_csv(DATALOC + "data4Johannes.txt", "global")
        gfas = read_csv(DATALOC + "timeseries_glob", "GFAS1p4")

        utils.plot_ts_panel(ax, [gfed, gfas],
                            "-",
                            "land_surface",
                            loc=LEGEND_LOC)

        ax.set_ylabel("Tg(C) month" + r'$^{-1}$', fontsize=settings.FONTSIZE)
        ax.set_ylim([0, 840])

        # sort formatting
        plt.xlim([1997, int(settings.YEAR) + 2])

        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)

        # sort labelling
        ax.text(0.02,
                0.9,
                "Global",
                transform=ax.transAxes,
                fontsize=settings.LABEL_FONTSIZE)

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

    #************************************************************************
    # Timeseries - 2019 version
    if True:
        majorLocator = MultipleLocator(5)
        fig, (ax1, ax2, ax3, ax4) = plt.subplots(4,
                                                 figsize=(8, 10),
                                                 sharex=True)

        data = read_csv(DATALOC + "timeseries_TAsi", "GFAS1p4")
        utils.plot_ts_panel(ax1, [data], "-", "land_surface", loc="")
        ax1.text(0.02,
                 0.9,
                 "(a) Tropical Asia",
                 transform=ax1.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax1.set_ylim([0, 160])

        data = read_csv(DATALOC + "timeseries_Arct", "GFAS1p4")
        utils.plot_ts_panel(ax2, [data], "-", "land_surface", loc="")
        ax2.text(0.02,
                 0.9,
                 "(b) Arctic",
                 transform=ax2.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax2.set_ylim([0, 12])

        data = read_csv(DATALOC + "timeseries_SEAu", "GFAS1p4")
        utils.plot_ts_panel(ax3, [data], "-", "land_surface", loc="")
        ax3.text(0.02,
                 0.9,
                 "(c) NSW & Victoria",
                 transform=ax3.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax3.set_ylim([0, 16])

        data = read_csv(DATALOC + "timeseries_SAme", "GFAS1p4")
        utils.plot_ts_panel(ax4, [data], "-", "land_surface", loc="")
        ax4.text(0.02,
                 0.9,
                 "(d) Southern America",
                 transform=ax4.transAxes,
                 fontsize=settings.LABEL_FONTSIZE)
        ax4.set_ylim([0, 160])

        # sort formatting
        plt.xlim([2003, int(settings.YEAR) + 2])
        fig.text(0.03,
                 0.5,
                 "Tg(C) per month",
                 fontsize=settings.FONTSIZE,
                 rotation="vertical")
        ax4.xaxis.set_major_locator(majorLocator)
        for tick in ax4.xaxis.get_major_ticks():
            tick.label.set_fontsize(settings.FONTSIZE)
        for ax in [ax1, ax2, ax3, ax4]:
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(settings.FONTSIZE)

        # sort labelling

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

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

        plt.close()

    #************************************************************************
    # Global Anomalies
    if True:
        #    cube = read_data(DATALOC + "anomaly{}from2003-2015_smooth.txt".format(settings.YEAR), 2.1021584473146504e-05)
        #    cube_list = iris.load(DATALOC + "anomaly{}from2003-{}_coarse20.grb".format(settings.YEAR, int(settings.YEAR)-1))
        cube_list = iris.load(
            DATALOC +
            "anomaly{}from2003-{}_coarse20.grb".format(settings.YEAR, 2010))

        # 2016 - these grib files have 6 identical fields (email from J Kaiser 10/3/2017)
        cube = cube_list[0]
        # convert from kg(C) m-2 s-1 to g(C) m-2 a-1
        print("remove factor 1.14 after 2018 run")
        cube.data = cube.data * 1000 * 60 * 60 * 24 * 365. * GFAS_FACTOR

        bounds = [-1000, -160, -80, -40, -10, -5, 5, 10, 40, 80, 160, 1000]
        bounds = [-1000, -100, -40, -10, -5, -1, 1, 5, 10, 40, 100, 1000]

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "BOB_anomalies{}".format(settings.YEAR), cube,
            settings.COLOURMAP_DICT["land_surface"], bounds,
            "Anomalies from 2003-{} (g C m".format(2010) + r'$^{-2}$' + " yr" +
            r'$^{-1}$' + ")")
        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "p2.1_BOB_anomalies{}".format(settings.YEAR),
            cube,
            settings.COLOURMAP_DICT["land_surface"],
            bounds,
            "Anomalies from 2003-{} (g C m".format(2010) + r'$^{-2}$' + " yr" +
            r'$^{-1}$' + ")",
            figtext="(af) Carbon Emissions from Biomass Burning")

    #************************************************************************
    # Global actuals
    if True:
        #    cube = read_data(DATALOC + "year2016_smooth.txt", 0)
        cube_list = iris.load(DATALOC +
                              "year{}_coarse20.grb".format(settings.YEAR))
        cube = cube_list[0]
        # convert from kg(C) m-2 s-1 to g(C) m-2 a-1
        print("remove factor 1.14 after 2018 run")
        cube.data = cube.data * 1000 * 60 * 60 * 24 * 365. * GFAS_FACTOR

        bounds = [0, 5, 10, 40, 80, 120, 160, 200, 240, 500]
        bounds = [0, 1, 5, 10, 40, 80, 120, 160, 200, 500]

        # adjust to mask out <1 gC/m2/yr (Feb 2018)
        cmap = plt.cm.YlOrBr
        cmaplist = [cmap(i) for i in range(cmap.N)]
        for i in range(30):
            cmaplist[i] = (0.75, 0.75, 0.75, 1.0)
        cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)

        cube.data = np.ma.masked_where(cube.data < 1, cube.data)

        print("using hard coded sequential colourmap")
        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "BOB_actuals{}".format(settings.YEAR), cube,
            cmap, bounds, "g C m" + r'$^{-2}$' + " yr" + r'$^{-1}$' + "")

    #************************************************************************
    # Global climatology
    if False:
        cube_list = iris.load(DATALOC + "clim2003-2015_smooth.grb")
        cube = cube_list[0]
        # convert from kg(C) m-2 s-1 to g(C) m-2 a-1
        cube.data = cube.data * 1000 * 60 * 60 * 24 * 365.

        bounds = [0, 5, 10, 40, 80, 120, 160, 200, 240, 500]

        print("using hard coded sequential colourmap")
        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "BOB_climatology{}".format(settings.YEAR),
            cube, plt.cm.YlOrBr, bounds,
            "g C m" + r'$^{-2}$' + " yr" + r'$^{-1}$' + "")

    return  # run_all_plots
Exemple #15
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
Exemple #16
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()
Exemple #17
0
def run_all_plots():

    #************************************************************************
    # Upper Tropospheric Humidity timeseries figure
    if True:
        HIRSSTART = 1979
        MWSTART = 1999
        ERASTART = 1979

        # smooth by 3 months
        hirs = read_ts(DATALOC + "hirs_data.aa", HIRSSTART, "HIRS", smooth=3)
        mw = read_ts(DATALOC + "mw_data.aa", MWSTART, "Microwave", smooth=3)
        era5 = read_ts(DATALOC + "era5_data.aa", ERASTART, "ERA5", smooth=3)

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

        utils.plot_ts_panel(ax, [hirs, mw, era5],
                            "-",
                            "hydrological",
                            loc=LEGEND_LOC,
                            ncol=3)

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

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

        plt.ylim([-2.0, 2.0])
        plt.xlim([1979, int(settings.YEAR) + 1.5])

        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 + "UTH_ts{}".format(settings.OUTFMT))
        plt.close()

    #************************************************************************
    # HIRS map
    if True:
        cube = read_map(DATALOC, "hirs")

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

        #    utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_UTH_{}_anoms_hirs".format(settings.YEAR), cube, settings.COLOURMAP_DICT["hydrological"], bounds, "Anomalies from 2001-2010 (% rh)", figtext = "(n) Upper Tropospheric Humidity")
        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "UTH_{}_anoms_hirs".format(settings.YEAR),
            cube, settings.COLOURMAP_DICT["hydrological"], bounds,
            "Anomalies from 2001-2010 (% rh)")

    #************************************************************************
    # MW map
    if True:
        cube = read_map(DATALOC, "mw")

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

        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "UTH_{}_anoms_mw".format(settings.YEAR), cube,
            settings.COLOURMAP_DICT["hydrological"], bounds,
            "Anomalies from 2001-2010 (% rh)")
        utils.plot_smooth_map_iris(
            settings.IMAGELOC + "p2.1_UTH_{}_anoms_mw".format(settings.YEAR),
            cube,
            settings.COLOURMAP_DICT["hydrological"],
            bounds,
            "Anomalies from 2001-2010 (% rh)",
            figtext="(j) Upper Tropospheric Humidity")

    return  # run_all_plots
Exemple #18
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
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
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
Exemple #21
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