Example #1
0
def hist_by_stability(metdat, catinfo, category, vertloc=80, basecolor='span'):
    ###########################################
    """
    make histograms separating the variable (colname) by stability class.
    stability is the list of column names containing stability flags
    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.
    """
    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=basecolor)

    metdat = metdat.groupby(stabcol)

    fig, ax = plt.subplots(len(stabconds),
                           1,
                           figsize=(4, 6),
                           sharex=True,
                           sharey=True)
    for ii, stab in enumerate(stabconds):
        data = metdat[varcol].get_group(stab).dropna()
        ax.flatten()[ii].hist(data,
                              facecolor=colors[ii],
                              edgecolor='k',
                              bins=50,
                              weights=np.ones(len(data)) / len(data),
                              density=False)
        ax.flatten()[ii].legend([stab], fontsize=10, frameon=False)

    ax.flatten()[0].set_title(r'$z={}$m'.format(vertloc))

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

    fig.tight_layout()

    return fig, ax
Example #2
0
def normalized_hist_by_stability(metdat, catinfo, vertloc=80):
    """**Get Normalized Stability Grouped Histogram Figure**.

    Plot the normalized 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.
    """

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

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

    hours = np.arange(24)
    newbottom = np.zeros(24)

    fig, ax = plt.subplots()
    for jj, cond in enumerate(stabconds):
        # Use this for missing data, also works for full data
        a = garb.loc[cond]
        b = a.index.tolist()
        c = a.values.tolist()
        for i in range(len(hours)):
            if (hours[i]) in b:
                pass
            else:
                b.insert(i, hours[i])
                c.insert(i, 0)

        d = pd.Series(data=c, index=b)
        ax.bar(hours, d, color=colors[jj], bottom=newbottom)
        newbottom += c  #<-- for if missing data, also works for full data

        #ax.bar(hours, garb.loc[cond], color=colors[jj], bottom=newbottom)
        #newbottom += garb.loc[cond]

    ax.set_ylabel('Probability [%]')
    ax.set_xlabel('Time of Day [Hour]')
    fig.legend(stabconds)
    #fig.legend(stabconds, loc=6, bbox_to_anchor=(1,0.5),framealpha=0)
    fig.tight_layout()

    return fig, ax
Example #3
0
def hist_by_stability(metdat, catinfo, category, vertloc=80, basecolor='span'):
    """**Get Stability Grouped Histogram Figure**.

    Plot the 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.        
        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.
    """

    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=basecolor)

    metdat = metdat.groupby(stabcol)

    fig, ax = plt.subplots(len(stabconds),
                           1,
                           figsize=(4, 6),
                           sharex=True,
                           sharey=True)
    for ii, stab in enumerate(stabconds):
        data = metdat[varcol].get_group(stab).dropna()
        ax.flatten()[ii].hist(data,
                              facecolor=colors[ii],
                              edgecolor='k',
                              bins=50,
                              weights=np.ones(len(data)) / len(data),
                              density=False)
        ax.flatten()[ii].legend([stab], fontsize=10, frameon=False)

    ax.flatten()[0].set_title(r'$z={}$m'.format(vertloc))

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

    fig.tight_layout()

    return fig, ax
Example #4
0
def stability_profile(metdat,
                      catinfo,
                      category=None,
                      vertloc=80,
                      basecolor='span'):
    ###########################################
    """
    Plot cumulative average profiles sorted by stability.
    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)
    colors = utils.get_colors(5, basecolor=basecolor)
    stabconds = utils.get_stabconds()

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

    plotdat = metdat.groupby(stab).mean()
    pdat = plotdat[catinfo['columns'][category]].T.iloc[ind]

    fig, ax = plt.subplots(figsize=(3.5, 5))

    for ii, cond in enumerate(stabconds):

        ax.plot(pdat[cond], vertlocs, color=colors[ii], label=cond)

    ax.set_ylabel('Probe Height [m]')
    ax.set_xlabel(catinfo['labels'][category])
    fig.legend(stabconds, loc=6, bbox_to_anchor=(1, 0.5), frameon=False)

    fig.tight_layout()

    return fig, ax
Example #5
0
def stability_profile(metdat,
                      catinfo,
                      category=None,
                      vertloc=80,
                      basecolor='cycle'):
    """**Get Stability Profile**.

    Plot the 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: '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

    stab, stabloc, ind = utils.get_vertical_locations(
        catinfo['columns']['stability flag'], location=vertloc)
    colors = utils.get_colors(5, basecolor=basecolor)
    stabconds = utils.get_stabconds()

    plotdat = metdat.groupby(stab).mean()
    pdat = plotdat[catinfo['columns'][category]].get_values()

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

    fig, ax = plt.subplots(figsize=(3.5, 5))
    for ii, cond in enumerate(stabconds):

        ax.plot(pdat[ii, ind], vertlocs, color=colors[ii])

    ax.set_ylabel('Probe Height [m]')
    ax.set_xlabel(catinfo['labels'][category])
    fig.legend(stabconds, loc=6, bbox_to_anchor=(1, 0.5), frameon=False)

    fig.tight_layout()

    return fig, ax
Example #6
0
def stacked_hist_by_stability(metdat, catinfo, category, vertloc=80):
    """**Get Stacked Stability Grouped Histogram Figure**.

    Plot the 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): 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')

    plotdat = metdat.groupby(stabcol)

    fig, ax = plt.subplots()
    temp = pd.DataFrame(
        {cond: plotdat[varcol].get_group(cond)
         for cond in stabconds})
    temp.plot.hist(
        ax=ax,
        stacked=True,
        color=colors,
        bins=35,
        edgecolor='k',
        legend=False,
        #    weights = np.ones(temp.shape) / len(temp.index),
        density=True)

    ax.set_xlabel(catinfo['labels'][category])
    ax.set_title(r'$z={}$m'.format(vertloc))
    fig.legend(stabconds, loc=6, bbox_to_anchor=(1, 0.5), frameon=False)

    fig.tight_layout()

    return fig, ax
Example #7
0
def stacked_hist_by_stability(metdat, catinfo, category, vertloc=80):
    ###########################################
    """
    make a stacked 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
        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')

    plotdat = metdat.groupby(stabcol)

    fig, ax = plt.subplots(figsize=(5, 3))
    temp = pd.DataFrame(
        {cond: plotdat[varcol].get_group(cond)
         for cond in stabconds})
    temp.plot.hist(
        ax=ax,
        stacked=True,
        color=colors,
        bins=35,
        edgecolor='k',
        legend=False,
        #    weights = np.ones(temp.shape) / len(temp.index),
        density=True)

    ax.set_xlabel(catinfo['labels'][category])
    # ax.set_title(r'$z={}$m'.format(vertloc))
    fig.legend(stabconds, loc=6, bbox_to_anchor=(1, 0.5), frameon=False)

    fig.tight_layout()

    return fig, ax
Example #8
0
def normalized_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
    """
    stabconds = utils.get_stabconds()
    stabcol, _, _ = utils.get_vertical_locations(
        catinfo['columns']['stability flag'], location=vertloc)
    colors = utils.get_colors(len(stabconds), basecolor='span')

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

    hours = np.arange(24)
    newbottom = np.zeros(24)

    fig, ax = plt.subplots(figsize=(5, 3))
    for jj, cond in enumerate(stabconds):

        ax.bar(hours, garb.loc[cond], color=colors[jj], bottom=newbottom)
        newbottom += garb.loc[cond]

    ax.set_ylabel('Probability [%]')
    ax.set_xlabel('Time of Day [Hour]')
    fig.legend(stabconds, loc=6, bbox_to_anchor=(1, 0.5), framealpha=0)
    fig.tight_layout()

    return fig, ax
Example #9
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
Example #10
0
def stability_winddir_scatter(metdat,
                              catinfo,
                              category,
                              vertloc=80,
                              basecolor='red',
                              exclude_angles=[(46, 228)]):
    """**Get Wind Direction Stability Scatter Figure**.

    Plot the wind direction stability scatter 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: 'red']: Provides the color code information to get from "utils.py".
        6. exclude_angles (tuple, list) [default: [(46, 228)]]: Defines the start and stop angles to shade out regions according to International Electrotechnical Commission (IEC) standards.

    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()
    colors = utils.get_colors(len(stabconds), basecolor='span')
    nrelcolors = utils.get_nrelcolors()

    # Set up data
    dircol, _, _ = utils.get_vertical_locations(
        catinfo['columns']['direction'], location=vertloc)
    varcol, vertloc, _ = utils.get_vertical_locations(
        catinfo['columns'][category], location=vertloc)
    stabcol, _, _ = utils.get_vertical_locations(
        catinfo['columns']['stability flag'], location=vertloc)

    # dirind = utils.get_nearest_direction(metdat[category])

    fig, ax = plt.subplots(len(stabconds),
                           1,
                           sharex=True,
                           sharey=True,
                           figsize=(6, 8))

    plotdat = metdat.groupby(stabcol)

    for ind, stabcond in enumerate(stabconds):

        ax.flatten()[ind].scatter(plotdat[dircol].get_group(stabcond),
                                  plotdat[varcol].get_group(stabcond),
                                  marker='o',
                                  facecolor=colors[ind],
                                  color='k',
                                  lw=0.5,
                                  alpha=0.7)

        ax.flatten()[ind].set_xlim([0, 360])
        # ax.flatten()[ind].set_ylim([0,120])
        ax.flatten()[ind].legend([stabcond], fontsize=12, loc=1, frameon=False)

        for ii in range(len(exclude_angles)):
            ax.flatten()[ind].axvspan(exclude_angles[ii][0],
                                      exclude_angles[ii][1],
                                      alpha=0.1,
                                      color=nrelcolors[basecolor][0])

        if ind == 0:
            ax.flatten()[ind].set_title(r'$z={}$ m'.format(vertloc))

    fig.tight_layout()
    fig.text(0.5, 0, r'Wind Direction [$^\circ$]', ha='center', va='center')
    fig.text(0,
             0.5,
             catinfo['labels'][category],
             ha='center',
             va='center',
             rotation='vertical')
    return fig, ax  #, leg
Example #11
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
Example #12
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
###########################################
Example #13
0
def stability_winddir_scatter(metdat,
                              catinfo,
                              category,
                              vertloc=80,
                              basecolor='red',
                              exclude_angles=[(46, 228)]):
    ###########################################
    """
    make scatter plot from pandas.Series wind direction and some other value of the same size. Includes blocked off angles from IEC standards.
    Subplots correspond to stability conditions from Obukhov length
    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.
        exclude_angles:
            tuple or list of tuples of start and stop angles to shade out regions according to IEC standards
    """

    stabconds = utils.get_stabconds()
    colors = utils.get_colors(5, basecolor='span')
    nrelcolors = utils.get_nrelcolors()

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

    # dirind = utils.get_nearest_direction(metdat[category])

    fig, ax = plt.subplots(5, 1, sharex=True, sharey=True, figsize=(6, 8))

    plotdat = metdat.groupby(stabcol)

    for ind, stabcond in enumerate(stabconds):

        ax.flatten()[ind].scatter(plotdat[dircol].get_group(stabcond),
                                  plotdat[varcol].get_group(stabcond),
                                  marker='o',
                                  facecolor=colors[ind],
                                  color='k',
                                  lw=0.5,
                                  alpha=0.7)

        ax.flatten()[ind].set_xlim([0, 360])
        # ax.flatten()[ind].set_ylim([0,120])
        ax.flatten()[ind].legend([stabcond], fontsize=12, loc=1, frameon=False)

        for ii in range(len(exclude_angles)):
            ax.flatten()[ind].axvspan(exclude_angles[ii][0],
                                      exclude_angles[ii][1],
                                      alpha=0.1,
                                      color=nrelcolors[basecolor][0])

        # if ind == 0:
        #      ax.flatten()[ind].set_title(r'$z={}$ m'.format(vertloc))

    fig.tight_layout()
    fig.text(0.5, 0, r'Wind Direction [$^\circ$]', ha='center', va='center')
    fig.text(0,
             0.5,
             catinfo['labels'][category],
             ha='center',
             va='center',
             rotation='vertical')
    return fig, ax  #, leg
Example #14
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
Example #15
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


###########################################
Example #16
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