for i, tsdata in enumerate([tseries, tseries_rel]):
    for varnm in varnms:
        if i == 0:
            ymin, ymax = ylims[varnm]
        else:
            ymin, ymax = ylims_rel[varnm]
        if varnm in ['MFC', 'PCP', 'HOWI'] and i == 1:
            legend_loc = 'lower left'
        else:
            legend_loc = 'upper left'
        suptitle = '%s (%s Onset/Retreat)' % (varnm, onset_nm)
        ts_plot_all(tsdata, comp_yrs, comp_keys, varnm, index, enso, ymin, ymax,
                    suptitle, figsize, legend_loc=legend_loc)

filestr = 'daily_tseries-onset_%s-enso_%s-%s' % (onset_nm, enso_nm, savestr)
atm.savefigs(savedir + filestr, 'pdf', merge=True)
plt.close('all')

# ----------------------------------------------------------------------
# Variability in Accumulated precip / MFC over climatology
if plot_acc_clim:
    for ts, daynm in zip([tseries, tseries_rel], ['day', 'dayrel']):
        plt.figure(figsize=(8, 10))
        for i, key in enumerate(['MFC_ACC', 'PCP_ACC']):
            plt.subplot(2, 1, i + 1)
            tsbar = ts[key].mean(dim='year')
            tsplus = tsbar + ts[key].std(dim='year')
            tsminus = tsbar - ts[key].std(dim='year')
            tsmax = ts[key].max(dim='year')
            tsmin = ts[key].min(dim='year')
            days = tsbar[daynm]
fig_kw = {'figsize' : (14, 10), 'sharex' : True, 'sharey' : True}
gridspec_kw = {'left' : 0.05, 'right' : 0.98, 'bottom' : 0.05, 'top' : 0.95,
               'wspace' : 0.04, 'hspace' : 0.1}
stipple_kw = {'markersize' : 2, 'markeredgewidth' : 1.5}
coeff = 'm'
suptitle = '%d-%dE Reg onto %s Onset - Reg Coefficients' % (lon1, lon2, onset_nm)
ylim, yticks = (-60, 60), np.arange(-60, 61, 20)

grp = atm.FigGroup(nrow, ncol, fig_kw=fig_kw, gridspec_kw=gridspec_kw,
                   suptitle=suptitle)
for varnm in varnms:
    grp.next()
    var = data['reg'][varnm + '_sector'][coeff]
    p = data['reg'][varnm + '_sector']['p']
    sector_plot(var, p, stipple_kw, grp, ylim, yticks)
atm.savefigs(savestr + 'sector_onset_' + onset_nm, 'pdf', merge=True)
plt.close('all')

# Lat-lon maps
plt_list = regdays + seasons
nrow = 2
ncol = len(plt_list)
fig_kw = {'figsize' : (14, 10), 'sharex' : True, 'sharey' : True}
gridspec_kw = {'left' : 0.05, 'right' : 0.95, 'bottom' : 0.05, 'top' : 0.95,
               'wspace' : 0.15, 'hspace' : 0.1}
stipple_kw = {'markersize' : 2, 'markeredgewidth' : 1.5}
coeff = 'm'
suptitle = 'Reg onto %s Onset - Reg Coefficients' % onset_nm
grp = atm.FigGroup(nrow, ncol, fig_kw=fig_kw, gridspec_kw=gridspec_kw,
                   suptitle=suptitle)
for varnm in varnms:
tt = onset_TT(T, north=north, south=south)

# Some weirdness going on in 1991, for now just set to NaN
# Troubleshoot later
for nm in ['ttn', 'tts', 'tseries']:
    vals = tt[nm].values
    vals = np.ma.masked_array(vals, abs(vals) > 1e30).filled(np.nan)
    tt[nm].values = vals

# Plot TTN and TTS
plot_tseries_together(tt[['ttn', 'tts']], tt['onset'].values,
                      suptitle=suptitle, standardize=False)

# Summary plot and timeseries in individual years
summarize_indices(years, tt['onset'])
plt.suptitle(suptitle)
plot_index_years(tt, suptitle=suptitle, yearnm='year', daynm='day')

if save:
    atm.savefigs(varname + '_', 'png')

# Plot contour map of pressure-level data
p_plot = 400
T_plot = T_p[p_plot]
y, d = 0, 80
lat = atm.get_coord(T_plot, 'lat')
lon = atm.get_coord(T_plot, 'lon')
axlims = (lat.min(), lat.max(), lon.min(), lon.max())
plt.figure()
atm.pcolor_latlon(T_plot[y, d], axlims=axlims)
def saveclose(name, isave, exts):
    if isave:
        for ext in exts:
            atm.savefigs(name, ext)
    plt.close('all')
def index_tseries(days, ind, ind_roll, titlestr):
    plt.plot(days, ind, label='daily')
    plt.plot(days, ind_roll, label='%d-day rolling' % nroll)
    plt.grid()
    plt.legend(loc='lower right')
    plt.title(titlestr)

plt.figure(figsize=(12, 10))
plt.subplot(221)
index_tseries(days, ds.howi_clim_norm, ds.howi_clim_norm_roll,
              'HOWI ' + yearstr + ' Climatology')
for yr in [0, 1, 2]:
    plt.subplot(2, 2, yr + 2)
    index_tseries(days, ds.howi_norm[yr], ds.howi_norm_roll[yr],
                  'HOWI %d' % years[yr])

# ----------------------------------------------------------------------
# Onset and retreat indices

summarize_indices(years, onset, retreat, 'HOWI')

# ----------------------------------------------------------------------
# Plot timeseries of each year
plot_index_years(howi)

# ----------------------------------------------------------------------
# Save figures
if isave:
    for ext in exts:
        atm.savefigs(namestr, ext)
            plt.suptitle(suptitle)
            yplot = 1
        else:
            yplot += 1

        plt.subplot(nrow, ncol, yplot)
        plotyear(chp[varnm], y, xlims, ylims[varnm])
        row, col = atm.subplot_index(nrow, ncol, yplot)
        if row == nrow:
            plt.xlabel("Day")
        else:
            plt.gca().set_xticklabels("")
        if col > 1:
            plt.gca().set_yticklabels("")
    if isavefigs:
        atm.savefigs("onset_changepoint_merged_" + varnm.upper(), "pdf")
        plt.close("all")

df = pd.DataFrame()
for key in ["onset", "retreat"]:
    for varnm in varnms:
        df["%s_%s" % (key, varnm.upper())] = chp[varnm][key].to_series()
atm.scatter_matrix(df, incl_p=True, incl_line=True, annotation_pos=(0.05, 0.7))
plt.suptitle("Merged Changepoints")

plt.figure(figsize=(8, 10))
for i, key in enumerate(["onset", "retreat"]):
    plt.subplot(2, 1, i + 1)
    for varnm in varnms:
        plt.plot(years, df["%s_%s" % (key, varnm.upper())], label=varnm.upper())
    plt.legend()
            plt.suptitle(suptitle)
            yplot = 1
        else:
            yplot += 1

        plt.subplot(nrow, ncol, yplot)
        plotyear(chp[varnm], y, xlims, ylims[varnm])
        row, col = atm.subplot_index(nrow, ncol, yplot)
        if row == nrow:
            plt.xlabel('Day')
        else:
            plt.gca().set_xticklabels('')
        if col > 1:
            plt.gca().set_yticklabels('')
    if isave:
        atm.savefigs('onset_changepoint_' + varnm.upper(), 'pdf')
        plt.close('all')

df = pd.DataFrame()
for key in ['onset', 'retreat']:
    for varnm in varnms:
        df['%s_%s' % (key, varnm.upper())] = chp[varnm][key].to_series()
        if incl_merged:
            key2 = '%s_%s_m' % (key, varnm.upper())
            df[key2] = chpm[varnm][key].to_series()
opts = {'incl_p' : True, 'incl_line' : True, 'annotation_pos' : (0.05, 0.7)}
if incl_merged:
    for nm in ['onset', 'retreat']:
        keys = [key for key in df.columns if key.startswith(nm)]
        atm.scatter_matrix(df[keys], **opts)
else: