Ejemplo n.º 1
0
def monthlyhourlyplot(metdat, catinfo, category=None, basecolor='span'):
    """**Get Monthly Hourly Averaged Profile**.

    Plot the monthly hourly averaged profile of a given variable (or category of variables) grouped by a given condition (or set of conditions).
    
    Parameters:
        1. metdat (Pandas DataFrame): The desired input data (Met Mast).
        2. catinfo (dictionary): Categorization information for the desired input data. Holds column names, labels, units, and save names.
        3. category (string) [default: None]: Specifies the category of information that is desired for plotting.
        4. basecolor (string) [default: 'span']: Provides the color code information to get from "utils.py".

    Returns:
        1. fig (Matplotlib Figure): The figure object for the desired input data and categories.
        2. ax (Matplotlib Axes): The axes object for the desired input data and categories.
    """

    if category is None:
        print('not sure what to plot...')
        pass

    months = utils.monthnames()
    colors = utils.get_colors(len(catinfo['columns'][category]),
                              basecolor=basecolor,
                              reverse=True)
    colnames, vertlocs, ind = utils.get_vertical_locations(
        catinfo['columns'][category], reverse=True)

    plotdat = metdat[colnames].groupby(
        [metdat.index.month.rename('month'),
         metdat.index.hour.rename('hour')]).mean()

    fig, ax = plt.subplots(4, 3, figsize=(9, 11), sharex=True, sharey=True)
    for iax in range(len(months)):
        for catitem in range(len(colnames)):
            ax.flatten()[iax].plot(plotdat[colnames[catitem]].xs(iax + 1),
                                   color=colors[catitem])
        ax.flatten()[iax].set_title(months[iax], fontsize=12)

    fig.text(0.5, 0.2, 'Time of Day [hour]', ha='center', va='center')
    leg = fig.legend([str(v) + ' m' for v in vertlocs],
                     loc='upper center',
                     bbox_to_anchor=(0, -0.825, 1, 1),
                     bbox_transform=plt.gcf().transFigure,
                     frameon=False,
                     ncol=2)
    fig.tight_layout()
    fig.subplots_adjust(bottom=0.25)
    fig.text(0,
             0.6125,
             catinfo['labels'][category],
             ha='center',
             va='center',
             rotation='vertical')

    return fig, ax
Ejemplo n.º 2
0
def monthly_hist(metdat, catinfo, category, vertloc=80, basecolor='blue'):
    ###########################################
    """
    Histogram of a given field without any sorting.
    Parameters:
        metdat:
            Pandas dataframe containing met mast data
        catinfo:
            dict containing categorization info for the metmast data. Fore each category, 
            catinfo holds column names, labels, units, and save names
        category:
            string specifying category of information to plot (e.g. 'speed', 'stability', etc.)
        vertloc:
            int or float describing the exact or approximate height of interest along the tower
        basecolor:
            string with the color code info to get from utils.
    """

    colors = utils.get_nrelcolors()
    color = colors[basecolor][0]
    months = utils.monthnames()

    # set up data
    varcol, vertloc, _ = utils.get_vertical_locations(
        catinfo['columns'][category], location=vertloc)

    temp = metdat.groupby(metdat.index.month)
    temp = temp[varcol]

    binwidth = (metdat[varcol].dropna().max() -
                metdat[varcol].dropna().min()) / 35
    bins = np.arange(metdat[varcol].dropna().min(),
                     metdat[varcol].dropna().max(), binwidth)

    fig, ax = plt.subplots(4, 3, figsize=(9, 9), sharex=True, sharey=True)

    for im, month in enumerate(months):
        data = temp.get_group(im + 1).dropna()
        ax.flatten()[im].hist(data,
                              bins=bins,
                              color=color,
                              edgecolor='k',
                              weights=np.ones(len(data)) / len(data) * 100)
        ax.flatten()[im].set_title(month, fontsize=12)

    fig.tight_layout()
    fig.text(0,
             0.5,
             'Frequency [%]',
             rotation='vertical',
             ha='center',
             va='center')
    fig.text(0.5, 0, catinfo['labels'][category], ha='center', va='center')

    return fig, ax
Ejemplo n.º 3
0
def monthly_hist(metdat, catinfo, category, vertloc=80, basecolor='blue'):
    """**Get Monthly Histogram Figure**.

    Plot the monthly histogram of a given variable (or category of variables) grouped by a given condition (or set of conditions).
    
    Parameters:
        1. metdat (Pandas DataFrame): The desired input data (Met Mast).
        2. catinfo (dictionary): Categorization information for the desired input data. Holds column names, labels, units, and save names.
        3. category (string): Specifies the category of information that is desired for plotting.
        4. vertloc (integer, float) [default: 80]: Describes the desired vertical location alond the tower for analysis.        
        5. basecolor (string) [default: 'blue']: Provides the color code information to get from "utils.py".

    Returns:
        1. fig (Matplotlib Figure): The figure object for the desired input data and categories.
        2. ax (Matplotlib Axes): The axes object for the desired input data and categories.
    """

    colors = utils.get_nrelcolors()
    color = colors[basecolor][0]
    months = utils.monthnames()

    # set up data
    varcol, vertloc, _ = utils.get_vertical_locations(
        catinfo['columns'][category], location=vertloc)

    temp = metdat.groupby(metdat.index.month)
    temp = temp[varcol]

    binwidth = (metdat[varcol].dropna().max() -
                metdat[varcol].dropna().min()) / 35
    bins = np.arange(metdat[varcol].dropna().min(),
                     metdat[varcol].dropna().max(), binwidth)

    fig, ax = plt.subplots(4, 3, figsize=(9, 9), sharex=True, sharey=True)

    for im, month in enumerate(months):
        data = temp.get_group(im + 1).dropna()
        ax.flatten()[im].hist(data,
                              bins=bins,
                              color=color,
                              edgecolor='k',
                              weights=np.ones(len(data)) / len(data) * 100)
        ax.flatten()[im].set_title(month, fontsize=12)

    fig.tight_layout()
    fig.text(0,
             0.5,
             'Frequency [%]',
             rotation='vertical',
             ha='center',
             va='center')
    fig.text(0.5, 0, catinfo['labels'][category], ha='center', va='center')

    return fig, ax
Ejemplo n.º 4
0
def monthlyhourlyplot(metdat, catinfo, category=None, basecolor='span'):
    ###########################################
    """
    Plot monthly average profiles against one another.
    Parameters:
        metdat:
            Pandas dataframe containing met mast data
        catinfo:
            dict containing categorization info for the metmast data. Fore each category,
            catinfo holds column names, labels, units, and save names
        category:
            string specifying category of information to plot (e.g. 'speed', 'stability', etc.)
        basecolor:
            string with the color code info to get from utils.
    """
    if category is None:
        print('not sure what to plot...')
        pass

    months = utils.monthnames()
    colors = utils.get_colors(len(catinfo['columns'][category]),
                              basecolor=basecolor,
                              reverse=True)
    colnames, vertlocs, ind = utils.get_vertical_locations(
        catinfo['columns'][category], reverse=True)

    plotdat = metdat[colnames].groupby([metdat.index.month,
                                        metdat.index.hour]).mean()

    fig, ax = plt.subplots(4, 3, figsize=(9, 11), sharex=True, sharey=True)
    for iax in range(len(months)):
        for catitem in range(len(colnames)):
            ax.flatten()[iax].plot(plotdat[colnames[catitem]].xs(iax + 1),
                                   color=colors[catitem])
        ax.flatten()[iax].set_title(months[iax], fontsize=12)

    fig.text(0.5, 0.2, 'Time of Day [hour]', ha='center', va='center')
    leg = fig.legend([str(v) + ' m' for v in vertlocs],
                     loc='upper center',
                     bbox_to_anchor=(0, -0.825, 1, 1),
                     bbox_transform=plt.gcf().transFigure,
                     frameon=False,
                     ncol=2)
    fig.tight_layout()
    fig.subplots_adjust(bottom=0.25)
    fig.text(0,
             0.6125,
             catinfo['labels'][category],
             ha='center',
             va='center',
             rotation='vertical')

    return fig, ax
Ejemplo n.º 5
0
def monthly_profile(metdat, catinfo, category=None, basecolor='cycle'):
    """**Get Monthly Profile**.

    Plot the monthly profile of a given variable (or category of variables) grouped by a given condition (or set of conditions).
    
    Parameters:
        1. metdat (Pandas DataFrame): The desired input data (Met Mast).
        2. catinfo (dictionary): Categorization information for the desired input data. Holds column names, labels, units, and save names.
        3. category (string) [default: None]: Specifies the category of information that is desired for plotting.
        4. basecolor (string) [default: 'cycle']: Provides the color code information to get from "utils.py".

    Returns:
        1. fig (Matplotlib Figure): The figure object for the desired input data and categories.
        2. ax (Matplotlib Axes): The axes object for the desired input data and categories.
    """

    if category is None:
        print('not sure what to plot...')
        pass

    months = utils.monthnames()
    colors = utils.get_colors(len(months), basecolor=basecolor)
    colnames, vertlocs, ind = utils.get_vertical_locations(
        catinfo['columns'][category])

    plotdat = metdat[colnames].groupby(metdat.index.month).mean()

    fig, ax = plt.subplots(figsize=(3.5, 5), sharex=True, sharey=True)
    for iax in range(len(months)):
        ax.plot(plotdat.xs(iax + 1), vertlocs, color=colors[iax])

    leg = ax.legend(months, loc=7, bbox_to_anchor=(1.75, 0.5), edgecolor='w')
    ax.set_ylabel('Probe Height [m]')
    ax.set_xlabel(catinfo['labels'][category])

    fig.tight_layout()

    return fig, ax
Ejemplo n.º 6
0
def monthly_profile(metdat, catinfo, category=None, basecolor='cycle'):
    ###########################################
    """
    Plot monthly average profiles against one another.
    Parameters:
        metdat:
            Pandas dataframe containing met mast data
        catinfo:
            dict containing categorization info for the metmast data. Fore each category,
            catinfo holds column names, labels, units, and save names
        category:
            string specifying category of information to plot (e.g. 'speed', 'stability', etc.)
        basecolor:
            string with the color code info to get from utils.
    """

    if category is None:
        print('not sure what to plot...')
        pass

    months = utils.monthnames()
    colors = utils.get_colors(len(months), basecolor=basecolor)
    colnames, vertlocs, ind = utils.get_vertical_locations(
        catinfo['columns'][category])

    plotdat = metdat[colnames].groupby(metdat.index.month).mean()

    fig, ax = plt.subplots(figsize=(3.5, 5), sharex=True, sharey=True)
    for iax in range(len(months)):
        ax.plot(plotdat.xs(iax + 1), vertlocs, color=colors[iax])

    leg = ax.legend(months, loc=7, bbox_to_anchor=(1.75, 0.5), edgecolor='w')
    ax.set_ylabel('Probe Height [m]')
    ax.set_xlabel(catinfo['labels'][category])

    fig.tight_layout()

    return fig, ax
Ejemplo n.º 7
0
import matplotlib.pyplot as plt
from colour import Color
from windrose import WindroseAxes
from calendar import monthrange, month_name
import pylab as p

import vis
import utils
import met_funcs

# Place input files here
#inputfiles_here = ['2013_January.csv','2013_February.csv','2013_March.csv','2013_April.csv','2013_May.csv','2013_June.csv','2013_July.csv','2013_August.csv','2013_September.csv','2013_October.csv','2013_November.csv','2013_December.csv']
#inputfiles_here = ['2012_August.csv']
#inputfiles_here = ['2013_September.csv']
year = 2013
inputfiles_here = [str(year) + '_' + s + '.csv' for s in utils.monthnames()]

# Load and filter data
actual_data = met_funcs.load_met_data(inputfiles_here)
actual_data = met_funcs.drop_nan_cols(actual_data)
actual_data = met_funcs.qc_mask(actual_data)

# Extract categorical information
keep_cats = met_funcs.categories_to_keep()
ex_cats = met_funcs.categories_to_exclude()
var_cats, var_units, var_labels, var_save = met_funcs.categorize_fields(
    actual_data, keep_cats, ex_cats)

# Extract more information
met_funcs.groom_data(actual_data, var_cats)
stab_conds, stab_cats = met_funcs.flag_stability(actual_data)
Ejemplo n.º 8
0
def monthly_stacked_hist_by_stability(metdat, catinfo, category, vertloc=80):
    """**Get Monthly Stacked Stability Grouped Histogram Figure**.

    Plot the monthly stacked stability grouped histogram of a given variable (or category of variables) grouped by a given condition (or set of conditions).
    
    Parameters:
        1. metdat (Pandas DataFrame): The desired input data (Met Mast).
        2. catinfo (dictionary): Categorization information for the desired input data. Holds column names, labels, units, and save names.
        3. category (string): Specifies the category of information that is desired for plotting.
        4. vertloc (integer, float) [default: 80]: Describes the desired vertical location alond the tower for analysis.        

    Returns:
        1. fig (Matplotlib Figure): The figure object for the desired input data and categories.
        2. ax (Matplotlib Axes): The axes object for the desired input data and categories.
    """

    stabconds = utils.get_stabconds()
    stabcol, _, _ = utils.get_vertical_locations(
        catinfo['columns']['stability flag'], location=vertloc)
    varcol, vertloc, _ = utils.get_vertical_locations(
        catinfo['columns'][category], location=vertloc)
    colors = utils.get_colors(len(stabconds), basecolor='span')
    months = utils.monthnames()

    plotdat = metdat.groupby([metdat.index.month, stabcol])
    plotdat = plotdat[varcol]

    fig, ax = plt.subplots(4, 3, figsize=(9, 10), sharex=True, sharey=True)

    for iax, month in enumerate(months):
        temp = pd.DataFrame(
            {cond: plotdat.get_group((iax + 1, cond))
             for cond in stabconds})
        temp.plot.hist(
            ax=ax.flatten()[iax],
            stacked=True,
            color=colors,
            bins=35,
            edgecolor='k',
            legend=False,
            #    weights = np.ones(temp.dropna().shape) / np.prod(temp.shape),
            density=True)
        ax.flatten()[iax].set_title(month)
        ax.flatten()[iax].set_ylabel('')

    # fig.legend(stabconds, loc=8, bbox_to_anchor=(0, -0.1), edgecolor='w')
    fig.text(0,
             0.58,
             'Frequency',
             ha='center',
             va='center',
             fontsize=14,
             rotation='vertical')
    leg = fig.legend(stabconds,
                     loc=9,
                     bbox_to_anchor=(0.55, 0.15),
                     frameon=False)
    fig.tight_layout()
    fig.subplots_adjust(bottom=0.21)
    fig.text(0.5,
             0.16,
             catinfo['labels'][category],
             ha='center',
             va='center',
             fontsize=14)

    return fig, ax  #, leg
Ejemplo n.º 9
0
def monthly_rose_fig(metdat,
                     catinfo,
                     category=None,
                     vertloc=80,
                     bins=6,
                     nsector=36,
                     ylim=None,
                     noleg=False):
    """**Get Monthly Wind Rose Figure**.

    Plot the monthly wind rose of a given variable (or category of variables) grouped by a given condition (or set of conditions).
    
    Parameters:
        1. metdat (Pandas DataFrame): The desired input data (Met Mast).
        2. catinfo (dictionary): Categorization information for the desired input data. Holds column names, labels, units, and save names.
        3. category (string) [default: None]: Specifies the category of information that is desired for plotting.
        4. vertloc (integer, float) [default: 80]: Describes the desired vertical location alond the tower for analysis.        
        5. bins (integer, list) [default: 6]: Indicates the number of equally spaced bins to divide the variable.
        6. nsector (integer) [default: 36]: Indicated the number of sector directions to divide the rose figure.
        7. ylim (float) [default: None]: Provides the maximum value for the frequency of observations and is used to plot different roses with uniform limits.
        8. noleg (Boolean) [default: False]: Determines whether or not there will be a legend to the figure.

    Returns:
        1. fig (Matplotlib Figure): The figure object for the desired input data and categories.
        2. ax (Matplotlib Axes): The axes object for the desired input data and categories.
        3. leg (Matplotlib Legend): The legend object for the desired input data and categories. 
    """

    # set up data
    dircol, _, _ = utils.get_vertical_locations(
        catinfo['columns']['direction'], location=vertloc)
    varcol, vertloc, _ = utils.get_vertical_locations(
        catinfo['columns'][category], location=vertloc)
    plotdat = metdat.groupby(metdat.index.month)
    winddir = plotdat[dircol]
    var = plotdat[varcol]

    months = utils.monthnames()
    # wind speed bins to use in wind roses
    # get var divisions set up
    if isinstance(bins, int):
        nbins = bins
    else:
        nbins = len(bins)

    # set up plotting colors
    colors = utils.get_colors(nbins - 1, basecolor='span')
    colors += ['#3A4246']  # add something dark to the end.
    colors = tuple(colors[0:nbins])

    fig = plt.figure(figsize=(9, 13))

    for iax, month in enumerate(months):

        ax = fig.add_subplot(4, 3, iax + 1, projection="windrose")

        ax.bar(winddir.get_group(iax + 1),
               var.get_group(iax + 1),
               bins=bins,
               nsector=36,
               colors=colors,
               linewidth=0.35,
               normed=True)

        # Set the tick labels font
        for label in (ax.get_xticklabels() + ax.get_yticklabels()):
            label.set_fontname('Arial')
            label.set_fontsize(12)
        ax.set_title(month, fontsize=12, y=1.15)

        if iax == 10:
            leg = plt.legend(loc=8,
                             ncol=2,
                             bbox_to_anchor=(0.5, -0.65),
                             frameon=False)
            leg.set_title(catinfo['labels'][category])
            fig.text(0.5,
                     -0.085,
                     r'$z={}$ m'.format(vertloc),
                     ha='center',
                     va='center')

    axes = fig.get_children()[1:]
    # adjust plot for specified max frequency
    if ylim is None:
        ylim = 0.0
        for iax, month in enumerate(months):
            ylim = np.max([ylim, axes[iax].get_ylim()[-1]])

    for iax, month in enumerate(months):
        axes[iax].set_ylim(0, ylim)
        axes[iax].set_yticks(np.linspace(0.0, ylim, 4))
        # print(axes[iax].get_yticks())
        axes[iax].set_yticklabels(
            [str(np.round(x, decimals=1)) for x in axes[iax].get_yticks()])

    fig.tight_layout()

    return fig, axes, leg
Ejemplo n.º 10
0
def monthly_stability_profiles(metdat,
                               catinfo,
                               category=None,
                               vertloc=80,
                               basecolor='span'):
    """**Get Monthly Stability Profile**.

    Plot the monthly stability profile of a given variable (or category of variables) grouped by a given condition (or set of conditions).
    
    Parameters:
        1. metdat (Pandas DataFrame): The desired input data (Met Mast).
        2. catinfo (dictionary): Categorization information for the desired input data. Holds column names, labels, units, and save names.
        3. category (string) [default: None]: Specifies the category of information that is desired for plotting.
        4. vertloc (integer, float) [default: 80]: Describes the desired vertical location alond the tower for analysis.
        5. basecolor (string) [default: 'span']: Provides the color code information to get from "utils.py".

    Returns:
        1. fig (Matplotlib Figure): The figure object for the desired input data and categories.
        2. ax (Matplotlib Axes): The axes object for the desired input data and categories.
    """

    if category is None:
        print('not sure what to plot...')
        pass

    stab, stabloc, ind = utils.get_vertical_locations(
        catinfo['columns']['stability flag'], location=vertloc)

    plotdat = metdat.groupby([metdat.index.month, stab])
    colors = utils.get_colors(5, basecolor='span')
    months = utils.monthnames()
    stabconds = utils.get_stabconds()

    # extract vertical locations of data from variable names
    _, vertlocs, ind = utils.get_vertical_locations(
        catinfo['columns'][category])

    fig, ax = plt.subplots(4, 3, figsize=(8, 13), sharex=True, sharey=True)
    for iax, month in enumerate(months):

        for ii, cond in enumerate(stabconds):

            pdat = plotdat[catinfo['columns'][category]].get_group(
                (iax + 1, cond)).mean()
            ax.flatten()[iax].plot(pdat[ind], vertlocs, color=colors[ii])

        ax.flatten()[iax].set_title(month)

    fig.text(0,
             0.58,
             'Probe Height [m]',
             ha='center',
             va='center',
             fontsize=14,
             rotation='vertical')
    leg = fig.legend(stabconds,
                     loc=9,
                     bbox_to_anchor=(0.55, 0.12),
                     frameon=False)

    fig.tight_layout()
    fig.subplots_adjust(bottom=0.175)
    fig.text(0.525,
             0.135,
             catinfo['labels'][category],
             ha='center',
             va='center',
             fontsize=14)

    return fig, ax
Ejemplo n.º 11
0
def normalized_monthly_hist_by_stability(metdat, catinfo, vertloc=80):
    """**Get Normalized Monthly Stability Grouped Histogram Figure**.

    Plot the normalized monthly stability grouped histogram of a given variable (or category of variables) grouped by a given condition (or set of conditions).
    
    Parameters:
        1. metdat (Pandas DataFrame): The desired input data (Met Mast).
        2. catinfo (dictionary): Categorization information for the desired input data. Holds column names, labels, units, and save names.
        3. vertloc (integer, float) [default: 80]: Describes the desired vertical location alond the tower for analysis.        

    Returns:
        1. fig (Matplotlib Figure): The figure object for the desired input data and categories.
        2. ax (Matplotlib Axes): The axes object for the desired input data and categories.
    """

    months = utils.monthnames()
    hours = np.arange(24)
    stabcol, _, _ = utils.get_vertical_locations(
        catinfo['columns']['stability flag'], location=vertloc)
    stabconds = utils.get_stabconds()
    colors = utils.get_colors(5, basecolor='span')

    temp = metdat[stabcol].dropna()
    plotdata = temp.groupby(
        [temp.index.month.rename('month'),
         temp.index.hour.rename('hour')]).value_counts(normalize=True)
    plotdata.index.names = ['month', 'hour', 'stabclass']
    temp = plotdata.reorder_levels(['month', 'stabclass', 'hour'])

    indexvals = [np.arange(1, 13), stabconds, np.arange(24)]
    indx = pd.MultiIndex.from_product(indexvals,
                                      names=['month', 'stabclass', 'hour'])
    temp = temp.reindex(index=indx).fillna(0.0)

    fig, ax = plt.subplots(4, 3, figsize=(9, 10), sharex=True, sharey=True)
    for ii, month in enumerate(months):
        newbottom = np.zeros(24)

        for jj, cond in enumerate(stabconds):

            pdat = temp.loc[ii + 1, cond]

            ax.flatten()[ii].bar(hours,
                                 pdat,
                                 color=colors[jj],
                                 bottom=newbottom)

            newbottom += pdat

    # fig.legend(stabconds, loc=8, bbox_to_anchor=(0, -0.1), edgecolor='w')
    fig.text(-0.02,
             0.58,
             'Probability [%]',
             ha='center',
             va='center',
             rotation='vertical')
    leg = fig.legend(stabconds,
                     loc=9,
                     bbox_to_anchor=(0.55, 0.125),
                     frameon=False)

    fig.tight_layout()
    fig.subplots_adjust(bottom=0.21)
    fig.text(0.5, 0.165, 'Time of Day [Hour]', ha='center', va='center')

    return fig, ax


###########################################
# End of Code
###########################################
Ejemplo n.º 12
0
def monthly_rose_fig(metdat,
                     catinfo,
                     category=None,
                     vertloc=80,
                     bins=6,
                     nsector=36,
                     ylim=None,
                     noleg=False):
    ###########################################
    """
    make wind rose from pandas.Series wind direction and some other value of the same size.
    Parameters:
        metdat:
            Pandas dataframe containing met mast data
        catinfo:
            dict containing categorization info for the metmast data. Fore each category,
            catinfo holds column names, labels, units, and save names
        category:
            string specifying category of information to plot (e.g. 'speed', 'stability', etc.)
        vertloc:
            int or float describing the exact or approximate height of interest along the tower
        bins:
            int specifying number of equally spaced bins to divide var.
            OR
            list of bin division limits (eg [0,4,8,12,16])
        nsector:
            number or direction sectors to divide rose
        ylim:
            optional float with maximum value for frequency of observations, use to
            plot different roses with uniform limits
        noleg:
            bool switch to turn legend off
    """

    # set up data
    dircol, _, _ = utils.get_vertical_locations(
        catinfo['columns']['direction'], location=vertloc)
    varcol, vertloc, _ = utils.get_vertical_locations(
        catinfo['columns'][category], location=vertloc)
    plotdat = metdat.groupby(metdat.index.month)
    winddir = plotdat[dircol]
    var = plotdat[varcol]

    months = utils.monthnames()
    # wind speed bins to use in wind roses
    # get var divisions set up
    if isinstance(bins, int):
        nbins = bins
    else:
        nbins = len(bins)

    # set up plotting colors
    colors = utils.get_colors(nbins - 1, basecolor='span')
    colors += ['#3A4246']  # add something dark to the end.
    colors = tuple(colors[0:nbins])

    fig = plt.figure(figsize=(9, 13))

    for iax, month in enumerate(months):

        ax = fig.add_subplot(4, 3, iax + 1, projection="windrose")

        ax.bar(winddir.get_group(iax + 1),
               var.get_group(iax + 1),
               bins=bins,
               nsector=36,
               colors=colors,
               linewidth=0.35,
               normed=True)

        # Set the tick labels font
        for label in (ax.get_xticklabels() + ax.get_yticklabels()):
            label.set_fontname('Arial')
            label.set_fontsize(12)
        ax.set_title(month, fontsize=12, y=1.15)

        if iax == 10:
            leg = plt.legend(loc=8,
                             ncol=2,
                             bbox_to_anchor=(0.5, -0.65),
                             frameon=False)
            leg.set_title(catinfo['labels'][category])
            fig.text(0.5,
                     -0.085,
                     r'$z={}$ m'.format(vertloc),
                     ha='center',
                     va='center')

    axes = fig.get_children()[1:]
    # adjust plot for specified max frequency
    if ylim is None:
        ylim = 0.0
        for iax, month in enumerate(months):
            ylim = np.max([ylim, axes[iax].get_ylim()[-1]])

    for iax, month in enumerate(months):
        axes[iax].set_ylim(0, ylim)
        axes[iax].set_yticks(np.linspace(0.0, ylim, 4))
        # print(axes[iax].get_yticks())
        axes[iax].set_yticklabels(
            [str(np.round(x, decimals=1)) for x in axes[iax].get_yticks()])

    fig.tight_layout()

    return fig, axes, leg
Ejemplo n.º 13
0
def monthly_stability_profiles(metdat,
                               catinfo,
                               category=None,
                               vertloc=80,
                               basecolor='span'):
    ###########################################
    """
    Plot monthly average profiles against one another.
    Parameters:
        metdat:
            Pandas dataframe containing met mast data
        catinfo:
            dict containing categorization info for the metmast data. Fore each category,
            catinfo holds column names, labels, units, and save names
        category:
            string specifying category of information to plot (e.g. 'speed', 'stability', etc.)
        vertloc:
            int or float describing the exact or approximate height of interest along the tower
        basecolor:
            string with the color code info to get from utils.
    """
    if category is None:
        print('not sure what to plot...')
        pass

    stab, stabloc, ind = utils.get_vertical_locations(
        catinfo['columns']['stability flag'], location=vertloc)

    plotdat = metdat.groupby([metdat.index.month, stab])
    colors = utils.get_colors(5, basecolor=basecolor)
    months = utils.monthnames()
    stabconds = utils.get_stabconds()

    # extract vertical locations of data from variable names
    _, vertlocs, ind = utils.get_vertical_locations(
        catinfo['columns'][category])

    fig, ax = plt.subplots(4, 3, figsize=(8, 13), sharex=True, sharey=True)
    for iax, month in enumerate(months):

        for ii, cond in enumerate(stabconds):

            pdat = plotdat[catinfo['columns'][category]].get_group(
                (iax + 1, cond)).mean()
            ax.flatten()[iax].plot(pdat[ind],
                                   vertlocs,
                                   color=colors[ii],
                                   label=cond)

        ax.flatten()[iax].set_title(month)

    fig.text(0,
             0.58,
             'Probe Height [m]',
             ha='center',
             va='center',
             fontsize=14,
             rotation='vertical')
    leg = fig.legend(stabconds,
                     loc=9,
                     bbox_to_anchor=(0.55, 0.12),
                     frameon=False)

    fig.tight_layout()
    fig.subplots_adjust(bottom=0.175)
    fig.text(0.525,
             0.135,
             catinfo['labels'][category],
             ha='center',
             va='center',
             fontsize=14)

    return fig, ax
Ejemplo n.º 14
0
def normalized_monthly_hist_by_stability(metdat, catinfo, vertloc=80):
    ###########################################
    """
    make a normlizec histogram of data separated by stability class.
    Parameters:
        metdat:
            Pandas dataframe containing met mast data
        catinfo:
            dict containing categorization info for the metmast data. Fore each category,
            catinfo holds column names, labels, units, and save names
        vertloc:
            int or float describing the exact or approximate height of interest along the tower
    """

    months = utils.monthnames()
    hours = np.arange(24)
    stabcol, _, _ = utils.get_vertical_locations(
        catinfo['columns']['stability flag'], location=vertloc)
    stabconds = utils.get_stabconds()
    colors = utils.get_colors(5, basecolor='span')

    temp = metdat[stabcol].dropna()
    plotdata = temp.groupby([temp.index.month,
                             temp.index.hour]).value_counts(normalize=True)
    plotdata.index.names = ['month', 'hour', 'stabclass']
    temp = plotdata.reorder_levels(['month', 'stabclass', 'hour'])

    indexvals = [np.arange(1, 13), stabconds, np.arange(24)]
    indx = pd.MultiIndex.from_product(indexvals,
                                      names=['month', 'stabclass', 'hour'])
    temp = temp.reindex(index=indx).fillna(0.0)

    fig, ax = plt.subplots(4, 3, figsize=(9, 10), sharex=True, sharey=True)
    for ii, month in enumerate(months):
        newbottom = np.zeros(24)

        for jj, cond in enumerate(stabconds):

            pdat = temp.loc[ii + 1, cond]
            ax.flatten()[ii].bar(hours,
                                 pdat,
                                 color=colors[jj],
                                 bottom=newbottom)
            newbottom += pdat
            ax.flatten()[ii].set_title(month)

    # fig.legend(stabconds, loc=8, bbox_to_anchor=(0, -0.1), edgecolor='w')
    fig.text(-0.02,
             0.58,
             'Probability [%]',
             ha='center',
             va='center',
             rotation='vertical')
    leg = fig.legend(stabconds,
                     loc=9,
                     bbox_to_anchor=(0.55, 0.145),
                     frameon=False)

    fig.tight_layout()
    fig.subplots_adjust(bottom=0.21)
    fig.text(0.5, 0.165, 'Time of Day [Hour]', ha='center', va='center')

    return fig, ax


###########################################
Ejemplo n.º 15
0
def monthly_stacked_hist_by_stability(metdat, catinfo, category, vertloc=80):
    ###########################################
    """
    make histograms of data separated by month and stability class.
    Parameters:
        metdat:
            Pandas dataframe containing met mast data
        catinfo:
            dict containing categorization info for the metmast data. Fore each category,
            catinfo holds column names, labels, units, and save names
        category:
            string specifying category of information to plot (e.g. 'speed', 'stability', etc.)
        vertloc:
            int or float describing the exact or approximate height of interest along the tower
    """
    stabconds = utils.get_stabconds()
    stabcol, _, _ = utils.get_vertical_locations(
        catinfo['columns']['stability flag'], location=vertloc)
    varcol, vertloc, _ = utils.get_vertical_locations(
        catinfo['columns'][category], location=vertloc)
    colors = utils.get_colors(len(stabconds), basecolor='span')
    months = utils.monthnames()

    plotdat = metdat.groupby([metdat.index.month, stabcol])
    plotdat = plotdat[varcol]

    fig, ax = plt.subplots(4, 3, figsize=(9, 10), sharex=True, sharey=True)

    for iax, month in enumerate(months):
        temp = pd.DataFrame(
            {cond: plotdat.get_group((iax + 1, cond))
             for cond in stabconds})
        temp.plot.hist(
            ax=ax.flatten()[iax],
            stacked=True,
            color=colors,
            bins=35,
            edgecolor='k',
            legend=False,
            #    weights = np.ones(temp.dropna().shape) / np.prod(temp.shape),
            density=True)
        ax.flatten()[iax].set_title(month)
        ax.flatten()[iax].set_ylabel('')

    # fig.legend(stabconds, loc=8, bbox_to_anchor=(0, -0.1), edgecolor='w')
    fig.text(0,
             0.58,
             'Frequency',
             ha='center',
             va='center',
             fontsize=14,
             rotation='vertical')
    leg = fig.legend(stabconds,
                     loc=9,
                     bbox_to_anchor=(0.55, 0.15),
                     frameon=False)
    fig.tight_layout()
    fig.subplots_adjust(bottom=0.21)
    fig.text(0.5,
             0.16,
             catinfo['labels'][category],
             ha='center',
             va='center',
             fontsize=14)

    return fig, ax  #, leg