예제 #1
0
    def draw(self, fig):

        """ Draw windrose plot of current data on figure """

        try:
            axes = WindroseAxes(fig, rect=[0.1, 0.1, 0.8, 0.8])
            fig.add_axes(axes)

            axes.bar(self.direction, self.windspeed, normed=True)

            axes.set_title("Windrose (by % in 6 bins)")
            legend = axes.legend(borderaxespad=-0.10, fontsize=8, bbox_to_anchor=(-0.2, 0))

            legend_title = "Wind Speed"

            try:
                #Try adding a unit to the legend title
                units = self.configmanager.get_units() # Get unit strings from config
                legend_title = legend_title + " " + units["Wind Speed"].strip()

            except (KeyError, ValueError):
                pass # If no units exists, or the config isn't valid, just use title without units

            legend.set_title(legend_title, prop={"size":8})
        except:
            raise
예제 #2
0
def all_sta_wind_rose():
    fig = plt.figure(figsize=(16, 16))
    rect = [[0.05, 0.55, 0.35, 0.35], [0.55, 0.55, 0.35, 0.35], [0.05, 0.05, 0.35, 0.35], [0.55, 0.05,0.35, 0.35]]
    plot = 0
    for station in station_dict.keys():
        wa = WindroseAxes(fig, rect[plot])
        fig.add_axes(wa)
        ANN, DJF, MAM, JJA, SON = load_AWS(station)
        # define data limits
        max_mod = max(ANN['FF_10m'])
        wa.set_title(station_dict[station], fontsize=28, color='dimgrey', pad=50)
        wa.axes.spines['polar'].set_visible(False)
        wa.tick_params(axis='both', which='both', labelsize=20, tick1On=False, tick2On=False, labelcolor='dimgrey', pad=10)
        wa.bar(ANN['WD'], ANN['FF_10m'], bins=np.arange(0, 20, 4), cmap=plt.get_cmap('viridis'), normed=True, opening=0.8, edgecolor='white')
        wa.set_yticks([5,10,15])
        wa.set_yticklabels([ '', '10%', '15%'])
        plot = plot + 1
    lgd = wa.set_legend(bbox_to_anchor=(-0.45, 1.))
    frame = lgd.get_frame()
    frame.set_facecolor('white')
    for ln in lgd.get_texts():
        plt.setp(ln, color='dimgrey', fontsize=24)
    lgd.get_frame().set_linewidth(0.0)
    if host == 'bsl':
        plt.savefig('/users/ellgil82/figures/Hindcast/Validation/wind_rose_all_stations_all_years.png')
        plt.savefig('/users/ellgil82/figures/Hindcast/Validation/wind_rose_all_stations_all_years.eps')
    elif host == 'jasmin':
        plt.savefig('/gws/nopw/j04/bas_climate/users/ellgil82/hindcast/figures/wind_rose_all_stations_all_years.png')
        plt.savefig('/gws/nopw/j04/bas_climate/users/ellgil82/hindcast/figures/wind_rose_all_stations_all_years.eps')
    plt.show()
예제 #3
0
def plotter(fdict):
    """ Go """
    import matplotlib
    matplotlib.use('agg')
    import matplotlib.pyplot as plt
    from windrose import WindroseAxes
    from matplotlib.patches import Rectangle
    ctx = get_context(fdict)

    fig = plt.figure(figsize=(6, 7.2), facecolor='w', edgecolor='w')
    rect = [0.08, 0.1, 0.8, 0.8]
    ax = WindroseAxes(fig, rect, axisbg='w')
    fig.add_axes(ax)
    ax.bar(ctx['df']['drct'].values, ctx['df']['smph'].values,
           normed=True, bins=[0, 2, 5, 7, 10, 15, 20], opening=0.8,
           edgecolor='white', nsector=18)
    handles = []
    for p in ax.patches_list:
        color = p.get_facecolor()
        handles.append(Rectangle((0, 0), 0.1, 0.3,
                                 facecolor=color, edgecolor='black'))
    legend = fig.legend(handles,
                        ('2-5', '5-7', '7-10', '10-15', '15-20', '20+'),
                        loc=(0.01, 0.03), ncol=6,
                        title='Wind Speed [%s]' % ('mph',),
                        mode=None, columnspacing=0.9, handletextpad=0.45)
    plt.setp(legend.get_texts(), fontsize=10)

    plt.gcf().text(0.5, 0.99, ctx['plottitle'],
                   fontsize=16, ha='center', va='top')
    plt.gcf().text(0.95, 0.12, "n=%s" % (len(ctx['df'].index),),
                   verticalalignment="bottom", ha='right')

    return fig, ctx['df']
예제 #4
0
def wind_rose(station, AWS_var, model_var):
    fig = plt.figure(figsize = (16,8))
    rect = [0.05, 0.1, 0.45, 0.6]
    wa = WindroseAxes(fig, rect)
    fig.add_axes(wa)
    # define data limits
    max_mod = max(np.mean(vars_yr['FF_10m'][:,lat_index14-1:lat_index14+1, lon_index14-1:lon_index14+1].data, axis = (1,2)))
    max_obs = max(AWS_var['FF'])
    wa.set_title('Observed', fontsize = 28, color = 'dimgrey', pad = 50)
    wa.axes.spines['polar'].set_visible(False)
    wa.tick_params(axis='both', which='both', labelsize=24, tick1On=False, tick2On=False, labelcolor='dimgrey', pad=10)
    wa.bar(AWS_var['WD'], AWS_var['FF'], bins = np.arange(0, max(max_mod, max_obs),4), cmap = plt.get_cmap('viridis'), normed = True,opening=0.8, edgecolor='white')
    wa.set_yticklabels([])
    rect = [0.55, 0.1, 0.45, 0.6]
    wa = WindroseAxes(fig, rect)
    fig.add_axes(wa)
    wa.set_title('Modelled', fontsize=28, color='dimgrey', pad = 50)
    wa.bar(np.mean(vars_yr['WD'][:,lat_index14-1:lat_index14+1, lon_index14-1:lon_index14+1].data, axis = (1,2)),
           np.mean(vars_yr['FF_10m'][:,lat_index14-1:lat_index14+1, lon_index14-1:lon_index14+1].data, axis = (1,2)),
           bins = np.arange(0, max(max_mod, max_obs),4), cmap = plt.get_cmap('viridis'),  normed = True, opening=0.8, edgecolor='white')
    lgd = wa.set_legend( bbox_to_anchor=(-0.5, 0.9))
    frame = lgd.get_frame()
    frame.set_facecolor('white')
    for ln in lgd.get_texts():
        plt.setp(ln, color='dimgrey', fontsize = 18)
    lgd.get_frame().set_linewidth(0.0)
    wa.axes.spines['polar'].set_visible(False)
    wa.set_yticklabels([])
    wa.tick_params(axis='both', which='both', labelsize=24, tick1On=False, tick2On=False, labelcolor='dimgrey', pad=10)
    plt.savefig('/users/ellgil82/figures/Hindcast/validation/wind_rose_' + station + '_' + year + '.png')
    plt.savefig('/users/ellgil82/figures/Hindcast/validation/wind_rose_' + station + '_' + year + '.eps')
    plt.show()
예제 #5
0
    def rose_diagram(self, direction, norm):

        """
        Plot rose diagram

        Inputs:
        ------
          - direction = 1D array
          - norm = 1D array
        """
        #Convertion
        #TR: not quite sure here, seems to change from location to location
        #    express principal axis in compass
        direction = np.mod(90.0 - direction, 360.0)

        #Create new figure
        fig = plt.figure(figsize=(18,10))
        plt.rc('font',size='22')
        rect = [0.1, 0.1, 0.8, 0.8]
        ax = WindroseAxes(fig, rect)#, axisbg='w')
        fig.add_axes(ax)
        #Rose
        ax.bar(direction, norm , normed=True, opening=0.8, edgecolor='white')
        #adjust legend
        l = ax.legend(shadow=True, bbox_to_anchor=[-0.1, 0], loc='lower left')
        plt.setp(l.get_texts(), fontsize=10)
        plt.xlabel('Rose diagram in % of occurrences - Colormap of norms')
        plt.show() 
예제 #6
0
    def rose_diagram(self, direction, norm):

        """
        Plot rose diagram

        Inputs:
          - direction = 1D array
          - norm = 1D array
        """
        #Convertion
        #TR: not quite sure here, seems to change from location to location
        #    express principal axis in compass
        direction = np.mod(90.0 - direction, 360.0)

        #Create new figure
        self._def_fig()  
        rect = [0.1, 0.1, 0.8, 0.8]
        ax = WindroseAxes(self._fig, rect)#, axisbg='w')
        self._fig.add_axes(ax)
        #Rose
        ax.bar(direction, norm , normed=True, opening=0.8, edgecolor='white')
        #adjust legend
        l = ax.legend(shadow=True, bbox_to_anchor=[-0.1, 0], loc='lower left')
        plt.setp(l.get_texts(), fontsize=10)
        plt.xlabel('Rose diagram in % of occurrences - Colormap of norms')
        self._plt.show() 
예제 #7
0
파일: p16.py 프로젝트: akrherz/iem
def plotter(fdict):
    """ Go """
    import matplotlib
    matplotlib.use('agg')
    import matplotlib.pyplot as plt
    from windrose import WindroseAxes
    from matplotlib.patches import Rectangle
    ctx = get_context(fdict)

    fig = plt.figure(figsize=(6, 7.2), facecolor='w', edgecolor='w')
    rect = [0.08, 0.1, 0.8, 0.8]
    ax = WindroseAxes(fig, rect, axisbg='w')
    fig.add_axes(ax)
    ax.bar(ctx['df']['drct'].values, ctx['df']['smph'].values,
           normed=True, bins=[0, 2, 5, 7, 10, 15, 20], opening=0.8,
           edgecolor='white', nsector=18)
    handles = []
    for p in ax.patches_list:
        color = p.get_facecolor()
        handles.append(Rectangle((0, 0), 0.1, 0.3,
                                 facecolor=color, edgecolor='black'))
    l = fig.legend(handles,
                   ('2-5', '5-7', '7-10', '10-15', '15-20', '20+'),
                   loc=(0.01, 0.03), ncol=6,
                   title='Wind Speed [%s]' % ('mph',),
                   mode=None, columnspacing=0.9, handletextpad=0.45)
    plt.setp(l.get_texts(), fontsize=10)

    plt.gcf().text(0.5, 0.99, ctx['plottitle'],
                   fontsize=16, ha='center', va='top')
    plt.gcf().text(0.95, 0.12, "n=%s" % (len(ctx['df'].index),),
                   verticalalignment="bottom", ha='right')

    return fig, ctx['df']
예제 #8
0
def main():

    loc = 'fl0'
    weatherDir = '/data1/ancillary_data/fl0/eol/'
    weatherFileTag = 'v2'
    iyear = 2010
    fyear = 2010

    wdir, wspeed, temp, rh, dtw = weatherout(loc, weatherDir, weatherFileTag,
                                             iyear, fyear)

    hours = []
    for k in dtw:
        hours.append(k.hour)

    hours = np.asarray(hours)

    inds = np.where((wspeed <= 10.0) & (hours > 8) & (hours < 18))[0]

    fig = plt.figure(figsize=(8, 8), dpi=80, facecolor='w', edgecolor='w')
    rect = [0.1, 0.1, 0.8, 0.8]
    ax = WindroseAxes(fig, rect, axisbg='w')
    fig.add_axes(ax)

    ax.bar(wdir[inds],
           wspeed[inds],
           normed=True,
           opening=0.9,
           edgecolor='white')
    ax.set_legend()

    #fig2 = plt.figure(figsize=(8, 8), dpi=80, facecolor='w', edgecolor='w')
    ax2 = WindAxes.from_ax()
    bins = np.arange(0, 10, 0.5)
    bins = bins[1:]
    ax2, params = ax2.pdf(wspeed[inds], bins=bins)

    ax3 = WindAxes.from_ax()
    bins = np.arange(0, 360, 15)
    bins = bins[1:]
    ax3, params = ax3.pdf(wdir[inds], bins=bins)

    # fig2,  ax2   = plt.subplots(figsize=(8,6))
    # ax2.scatter(wdir, wspeed, facecolors='red', edgecolors='black', s=35)
    # ax2.grid(True)

    plt.show(block=False)

    pdfsav = PdfPages('/data/iortega/results/fl0/windrose.pdf')
    pdfsav.savefig(fig, dpi=200)
    pdfsav.close()
    user_input = raw_input('Press any key to exit >>> ')
    sys.exit()
def plot_roses(filename,
               vdir,
               mag,
               nsector=16,
               bins=10,
               title=None,
               legtitle=None,
               dpi=150,
               figsize=(10, 10),
               tfont=17,
               lfont=14):
    """
    Plots the rose chart 
    from wind data and
    saves it to png file.
    """
    fig = plt.figure(figsize=figsize)
    # [left, bottom, width, height] as a fraction of total figure size
    right_rectangle = [0.05, 0.05, 0.85, 0.8]

    ax = WindroseAxes(fig, right_rectangle)
    fig.add_axes(ax)
    # ax.bar(wind['dir'], wind['sp'], normed=True, opening=0.9, edgecolor='white', bins=np.logspace(-1,1.3, 10), nsector=16)
    # ax.bar(wind['dir'], wind['sp'], normed=True, opening=0.9, edgecolor='white', bins=np.linspace(0,max(wind['sp']), 10), nsector=16)
    ax.bar(vdir,
           mag,
           normed=True,
           opening=0.9,
           edgecolor='white',
           bins=bins,
           nsector=nsector)
    if title:
        ax.set_title("{}".format(title), position=(0.5, 1.1), fontsize=tfont)

    cfont = max([8, lfont - 2])
    ax.tick_params(axis='both', which='major', labelsize=cfont)

    ax.set_legend()
    if legtitle:
        ax.legend(title='{}'.format(legtitle), loc=(0.0, 0.0))
    #used to pretty up the printing around of wind occurent frequencies
    tictic = ax.get_yticks()
    ax.set_yticks(np.arange(0, tictic[-1], tictic[-1] / len(tictic)))
    ax.yaxis.set_major_formatter(tkr.FormatStrFormatter('%2.0f'))

    if isinstance(filename, list):
        for item in filename:
            fig.savefig(item, dpi=dpi)
    else:
        fig.savefig(filename, dpi=dpi)
    plt.close()
    return 0
예제 #10
0
    def wros(self, ws, wd, maxi=10, dev=None, date=None, base=None):
        '''Plot a wind rose given an array of wind speed and wind direction'''

        fig = plt.figure(figsize=(30, 30),
                         dpi=150,
                         facecolor='w',
                         edgecolor='w')
        rect = [0.1, 0.1, 0.8, 0.8]
        ax = WindroseAxes(fig, rect, axisbg='w')
        fig.add_axes(ax, fontsize=12)
        try:
            ax.bar(wd,
                   ws,
                   normed=True,
                   opening=1,
                   edgecolor='white',
                   bins=[0, 2, 6, 12, 20, 29, 39, 50])
            ax.set_rmax(12)
            ax.set_radii_angle()
            l = ax.legend(loc=(1, 0))
            if self.periods == None:
                if base != None and date != None:
                    title = 'Wind rose at ' + str(
                        self.height) + 'm and at ' + str(
                            self.selected_cell[0]) + ' in ' + str(
                                date) + ' during the ' + str(
                                    base) + ' by ' + str(dev)
                elif base != None:
                    title = 'Wind rose at ' + str(
                        self.height) + 'm and at ' + str(
                            self.selected_cell[0]) + ' during the ' + str(
                                base) + ' by ' + str(dev)
                elif date != None:
                    title = 'Wind rose at ' + str(
                        self.height) + 'm and at ' + str(
                            self.selected_cell[0]) + ' in ' + str(
                                date) + ' by ' + str(dev)
                else:
                    title = 'Wind rose at ' + str(
                        self.height) + 'm and at ' + str(
                            self.selected_cell[0]) + ' by ' + str(dev)
            else:
                title = 'Wind statistics at ' + str(
                    self.height) + 'm and at ' + str(
                        self.selected_cell[0]) + str(
                            self.periods) + ' by ' + str(dev)
            plt.setp(l.get_texts(), fontsize=12)
            plt.title(title, fontsize=12, y=1.07)
            plt.show()
        except ValueError:
            print 'No windrose for ' + str(dev)
예제 #11
0
def main():

    loc = 'fl0'
    weatherDir     = '/data1/ancillary_data/fl0/eol/'
    weatherFileTag = 'v2'
    iyear = 2010
    fyear = 2016


    wdir, wspeed, temp, rh, dtw = weatherout(loc, weatherDir, weatherFileTag, iyear, fyear )
   
    hours = []
    for k in dtw:
        hours.append(k.hour)

    hours = np.asarray(hours)
    
    inds = np.where( (wspeed <= 10.0) & (hours > 8) & (hours < 18) )[0]
    

    fig = plt.figure(figsize=(8, 8), dpi=80, facecolor='w', edgecolor='w')
    rect = [0.1, 0.1, 0.8, 0.8]
    ax = WindroseAxes(fig, rect, axisbg='w')
    fig.add_axes(ax)

    ax.bar(wdir[inds], wspeed[inds], normed=True, opening=0.9, edgecolor='white')
    ax.set_legend()

    #fig2 = plt.figure(figsize=(8, 8), dpi=80, facecolor='w', edgecolor='w')
    ax2 = WindAxes.from_ax()
    bins = np.arange(0, 10 , 0.5)
    bins = bins[1:]
    ax2, params = ax2.pdf(wspeed[inds], bins=bins)

    ax3 = WindAxes.from_ax()
    bins = np.arange(0, 360, 15)
    bins = bins[1:]
    ax3, params = ax3.pdf(wdir[inds], bins=bins)

    # fig2,  ax2   = plt.subplots(figsize=(8,6))
    # ax2.scatter(wdir, wspeed, facecolors='red', edgecolors='black', s=35)
    # ax2.grid(True)        

    plt.show(block=False)

    pdfsav = PdfPages('/data/iortega/results/fl0/windrose.pdf')
    pdfsav.savefig(fig,dpi=200)
    pdfsav.close()
    user_input = raw_input('Press any key to exit >>> ')
    sys.exit()    
예제 #12
0
파일: p16.py 프로젝트: stormchas4/iem
def plotter(fdict):
    """ Go """
    ctx = get_context(fdict)

    fig = plt.figure(figsize=(6, 7.2), facecolor="w", edgecolor="w")
    rect = [0.08, 0.1, 0.8, 0.8]
    ax = WindroseAxes(fig, rect, facecolor="w")
    fig.add_axes(ax)
    ax.bar(
        ctx["df"]["drct"].values,
        ctx["df"]["smph"].values,
        normed=True,
        bins=[0, 2, 5, 7, 10, 15, 20],
        opening=0.8,
        edgecolor="white",
        nsector=18,
    )
    handles = []
    for p in ax.patches_list:
        color = p.get_facecolor()
        handles.append(
            Rectangle((0, 0), 0.1, 0.3, facecolor=color, edgecolor="black"))
    legend = fig.legend(
        handles,
        ("2-5", "5-7", "7-10", "10-15", "15-20", "20+"),
        loc=(0.01, 0.03),
        ncol=6,
        title="Wind Speed [%s]" % ("mph", ),
        mode=None,
        columnspacing=0.9,
        handletextpad=0.45,
    )
    plt.setp(legend.get_texts(), fontsize=10)

    plt.gcf().text(0.5,
                   0.99,
                   ctx["plottitle"],
                   fontsize=16,
                   ha="center",
                   va="top")
    plt.gcf().text(
        0.95,
        0.12,
        "n=%s" % (len(ctx["df"].index), ),
        verticalalignment="bottom",
        ha="right",
    )

    return fig, ctx["df"]
예제 #13
0
def animate_windrose_graph(i):
    all_data_map=data_service.get_all_data_map()
    is_active = data_service.get_active()
    if is_active == "1_3":
        data_service.update_all_data_map(data_service.get_start_date(), data_service.get_end_date())

        ws = my_service.restore_lost_data(all_data_map['FF'])
        wd = my_service.restore_lost_data(all_data_map['dd'])

        ws_scale_1 = tab1_service.map_speed_to_scale_one(ws)
        wd = tab1_service.map_compass_to_degrees(wd)

        # hide axes
        windrose_graph_fig.patch.set_visible(False)
        windrose_graph_ax.axis('off')
        windrose_graph_ax.axis('tight')

        ws_frequency_map = tab1_service.map_ws_by_frequency(ws)
        final_data = [list(ws_frequency_map.keys()), list(ws_frequency_map.values())]
        table = windrose_graph_ax.table(cellText=final_data, loc='top', cellLoc='center',
                                        rowLabels=[" м/с ", " % "], bbox=[0., 0., 0.23, .28])
        windrose_graph_fig.subplots_adjust(bottom=0.6)
        table.auto_set_font_size(False)
        table.set_fontsize(7)
        for (row, col), cell in table.get_celld().items():
            if row == 0:
                cell.set_text_props(fontproperties=FontProperties(weight='normal', size=7))
        for key, cell in table.get_celld().items():
            cell.set_linewidth(0.5)

        # windrose_graph_fig.clear()
        rect = [0.1, 0.1, 0.8, 0.8]
        wa = WindroseAxes(windrose_graph_fig, rect)
        windrose_graph_fig.add_axes(wa)
        windrose_graph_ax.grid()
        wa.bar(wd, ws_scale_1, normed=True, opening=0.8, edgecolor='white')
        # wa.set_legend()
        wa.set_legend(title="інтенсивність", loc="upper right")
예제 #14
0
        tstr = '%s Visibility' % (stns[j])
        pyplot.title(tstr, size=14)
        pngnm = '%s_VisHist.png' % (stns[j])
        fig.savefig(pngnm, bbox_inches=0)
        pyplot.close()

        # A Rose?
        fig = pyplot.figure(figsize=(7.5, 6), facecolor='w', edgecolor='w')
        rect = [0.08, 0.1, 0.8, 0.8]
        ax = WindroseAxes(fig, rect, facecolor='w')
        fig.add_axes(ax)

        ax.bar(wndsb['WindDir'],
               wndsb['Visibility'],
               normed=True,
               bins=[0, 0.3, 1.1, 2.1, 3.1, 4.1, 5.1],
               opening=0.8,
               edgecolor='white',
               nsector=18,
               cmap=rdmp)
        #        ax.set_legend()
        handles = []
        for p in ax.patches_list:
            color = p.get_facecolor()
            handles.append(
                Rectangle((0, 0), 0.1, 0.3, facecolor=color,
                          edgecolor='black'))
        legend = fig.legend(handles, ('< 0.5', '0.5-1.0', '1.0-2.0', '2.0-3.0',
                                      '3.0-4.0', '4.0-5.0', '> 5.0'),
                            loc=(0.75, 0.03),
                            ncol=2,
                            title='Visibility',
예제 #15
0
from windrose import WindroseAxes
from matplotlib import pyplot as plt
import matplotlib.cm as cm
import numpy as np
from windrose import WindroseAxes
from matplotlib import pyplot as plt
import numpy as np

kmh_to_ms = 0.277778
# Decembre 2020
ws = [
    5.6 * kmh_to_ms, 6.8 * kmh_to_ms, 6.4 * kmh_to_ms, 4.5 * kmh_to_ms,
    3.5 * kmh_to_ms, 5 * kmh_to_ms, 5.1 * kmh_to_ms
]
wd = [45, 45, 67.5, 67.5, 45, 45, 45]

# Février 2021
# ws = [5.60*kmh_to_ms, 2.90*kmh_to_ms, 2.90*kmh_to_ms, 3.40*kmh_to_ms, 5.00*kmh_to_ms, 6.30*kmh_to_ms, 3.70*kmh_to_ms]
# wd = [135, 45, 90, 90, 90, 112.5, 112.5]

fig = plt.figure()
rect = [0.125, 0.125, 0.75, 0.75]
# rect = [0.5, 0.5, 0.5, 0.5]
wa = WindroseAxes(fig, rect)
fig.add_axes(wa)
wa.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')
wa.set_legend(bbox_to_anchor=(1, -0.08), title="WIND SPEED\n(m/s)")

plt.show()
예제 #16
0
def plot_mag_vel_graphs(deployment,
                        magnitude_mean_df,
                        direction_mean_df,
                        no_nan_dir_mag_df,
                        water_cell_range_list,
                        mag_dir_cells_df,
                        selected_cells,
                        velocity_north_df,
                        velocity_east_df,
                        mean_df,
                        subset_title='',
                        subset=''):
    """ (str, df, df, df, lst[int], df, lst[int], df, df, str, str) -> fig, fig, fig, 
    fig
                                                                                                                                 
    deployment (str) is defined as ID_sitename
    The magnitude_mean_df is defined in the notebook                                                                            
    The direction_mean_df is defined in the notebook
    The no_nan_dir_mag_df is defined in the notebook
    list[int] for water_cell_range_list (y axis for plotting) defined in
    notebook
    The mag_dir_cells_df is defined in the notebook
    The list of selected_cells [int,int,int] is defined at the beginning of the
    notebook 
    string defining whether the data is pre/post subset (e.g. 'presubset' or
    'postsubset') to be used in titles
    velocity_east_df is defined earlier in the notebook"""
    #mean dir, mag, nan
    matplotlib.rcParams.update({'font.size': 15})
    fig = plt.figure(figsize=(10, 15))

    gs1 = gridspec.GridSpec(3, 3, wspace=0.4)

    ax1 = plt.subplot(gs1[:, :-1])
    ax1.plot(magnitude_mean_df.mean_magnitude,
             water_cell_range_list,
             color='b')
    ax1.yaxis.set_ticks(range(1, (max(water_cell_range_list) + 1), 1))
    ax1.grid(axis='y')
    ax1.set_xlabel('mean magnitude (m/sec)', color='b')
    ax1.set_ylabel('cell number')
    ax1.tick_params('x', colors='b')
    for index in range(3):
        plt.axhline(y=selected_cells[index], color='k')

    ax2 = plt.subplot(gs1[:, :-1])
    ax2 = ax1.twiny()
    ax2.plot(direction_mean_df, water_cell_range_list, color='g')
    ax2.set_xlabel('mean direction (deg mag)', color='g')
    ax2.tick_params('x', colors='g')
    ax2.set_xticks([0, 90, 180, 270])
    ax2.set_xlim(0, 360)

    for angle in [90, 180, 270]:
        plt.axvline(x=angle, linestyle='--', lw='1', color='k')

    ax3 = plt.subplot(gs1[:, -1])
    ax3.plot(no_nan_dir_mag_df, water_cell_range_list, color='k')
    ax3.set_xlabel('Number of NaNs')
    ax3.yaxis.set_ticks(range(1, (max(water_cell_range_list) + 1), 1))
    ax3.grid(axis='y')

    for index in range(3):
        plt.axhline(y=selected_cells[index], color='k')

    plt.savefig("{0}_Mean_Direction_and_Magnitude_{1}".format(
        deployment, subset))

    #mag vs time
    plt.figure(figsize=(200, 10))
    plt.plot(mag_dir_cells_df[str("cell_{}_magnitude".format(
        selected_cells[2]))])
    plt.plot(mag_dir_cells_df[str("cell_{}_magnitude".format(
        selected_cells[1]))])
    plt.plot(mag_dir_cells_df[str("cell_{}_magnitude".format(
        selected_cells[0]))])
    plt.title("{0} Magnitude {1}".format(deployment, subset))
    plt.ylabel('Magnitude (m/s)')
    plt.xlabel('Date (YYY-MM-DD)')
    #plt.xlim(min(mag_dir_cells_df.index)-40, max(mag_dir_cells_df.index)+40) #sets the size of the blank space at the edge of the plot
    plt.legend()
    plt.grid()
    plt.savefig("{0}_Magnitude_{1}.png".format(deployment, subset))

    #vel north and east vs time
    fig, (ax1, ax2) = plt.subplots(nrows=2,
                                   ncols=1,
                                   sharex=True,
                                   figsize=(100, 15))

    ax1.plot(velocity_north_df[str("cell_{}_velocity".format(
        selected_cells[2]))])
    ax1.plot(velocity_north_df[str("cell_{}_velocity".format(
        selected_cells[1]))])
    ax1.plot(velocity_north_df[str("cell_{}_velocity".format(
        selected_cells[0]))])
    ax1.set_ylabel('velocity North (m/sec)')
    ax1.grid()
    ax1.legend()

    ax2.plot(velocity_east_df[str("cell_{}_velocity".format(
        selected_cells[2]))])
    ax2.plot(velocity_east_df[str("cell_{}_velocity".format(
        selected_cells[1]))])
    ax2.plot(velocity_east_df[str("cell_{}_velocity".format(
        selected_cells[0]))])
    ax2.set_ylabel('Velocity East (m/sec))')
    ax2.grid()
    ax2.legend()

    plt.xlabel('Date (YYY-MM-DD)')
    #plt.xlim(min(mag_dir_cells_df.index)-40, max(mag_dir_cells_df.index)+40) #sets the size of the blank space at the edge of the plot

    plt.suptitle("{0} Velocity North and East vs Time {1}".format(
        deployment, subset))
    plt.savefig("{0}_Velocity_North_and_East_vs_Time_{1}".format(
        deployment, subset))

    #current rose
    fig = plt.figure(figsize=(10, 10))
    rect = [0.05, 0.05, 0.8, 0.8]
    wa = WindroseAxes(fig, rect)
    fig.add_axes(wa)
    wa.bar(mean_df.MeanDirection,
           mean_df.MeanSpeed,
           bins=6,
           normed=True,
           opening=0.8,
           edgecolor='white')
    plt.legend(fontsize=20)
    plt.title(
        "{0} {1} \nMean Velocity (m/Sec) - radial values indicate percentage of occurance"
        .format(deployment, subset),
        size=15)
    leg = plt.legend(0)
    #Sort out units if you changed to knots
    leg.set_title('Velocity - (m/Sec)')
    plt.savefig("{}_Current_Rose_Presubset".format(deployment))
예제 #17
0
        fig.savefig(pngnm, bbox_inches=0)
        pyplot.close()

        wndsb = wndsb[(wndsb['WindSpeed'] > 0)]
        # A Rose?
        fig = pyplot.figure(figsize=(7.5, 6), facecolor='w', edgecolor='w')
        rect = [0.08, 0.1, 0.8, 0.8]
        ax = WindroseAxes(fig, rect, facecolor='w')
        fig.add_axes(ax)
        #ax.bar(wndsb['WindDir'],wndsb['WindSpeed'],normed=True,opening=0.8,edgecolor='white')
        #ax.set_legend()

        ax.bar(wndsb['WindDir'],
               wndsb['WindSpeed'],
               normed=True,
               bins=[0, 2, 5, 7, 10, 15, 20],
               opening=0.8,
               edgecolor='white',
               nsector=36)
        handles = []
        pctr = 0
        for p in ax.patches_list:
            color = p.get_facecolor()
            # Skip the first bin
            if pctr > 0:
                handles.append(
                    Rectangle((0, 0),
                              0.1,
                              0.3,
                              facecolor=color,
                              edgecolor='black'))
예제 #18
0
def _make_plot(station, sknt, drct, units, nsector, rmax, hours, months,
               sname, minvalid, maxvalid, level, bins):
    """Generate a matplotlib windrose plot

    Args:
      station (str): station identifier
      sknt (list): list of wind obs
      drct (list): list of wind directions
      units (str): units of wind speed
      nsector (int): number of bins to use for windrose
      rmax (float): radius of the plot
      hours (list): hour limit for plot
      month (list): month limit for plot
      sname (str): station name
      minvalid (datetime): minimum observation time
      maxvalid (datetime): maximum observation time
      level (int): RAOB level in hPa of interest
      bins (list): values for binning the wind speeds

    Returns:
      matplotlib.Figure
    """
    # Generate figure
    fig = plt.figure(figsize=(7, 7), dpi=80, facecolor='w', edgecolor='w')
    rect = [0.15, 0.15, 0.7, 0.7]
    ax = WindroseAxes(fig, rect, axisbg='w')
    fig.add_axes(ax)
    wu = WINDUNITS[units] if level is None else RAOB_WINDUNITS[units]
    if len(bins) > 0:
        wu['bins'] = bins
        wu['binlbl'] = []
        for i, mybin in enumerate(bins[1:-1]):
            wu['binlbl'].append("%g-%g" % (mybin, bins[i+2]))
        wu['binlbl'].append("%g+" % (bins[-1],))
    ax.bar(drct, sknt, normed=True, bins=wu['bins'], opening=0.8,
           edgecolor='white', nsector=nsector, rmax=rmax)
    handles = []
    for p in ax.patches_list:
        color = p.get_facecolor()
        handles.append(plt.Rectangle((0, 0), 0.1, 0.3,
                                     facecolor=color, edgecolor='black'))
    l = fig.legend(handles, wu['binlbl'], loc=(0.01, 0.01),
                   ncol=6,
                   title='Wind Speed [%s]' % (wu['abbr'],),
                   mode=None, columnspacing=0.9, handletextpad=0.45)
    plt.setp(l.get_texts(), fontsize=10)
    # Now we put some fancy debugging info on the plot
    tlimit = "Time Domain: "
    if len(hours) == 24 and len(months) == 12:
        tlimit = "All Year"
    if len(hours) < 24:
        if len(hours) > 4:
            tlimit += "%s-%s" % (
                    datetime.datetime(2000, 1, 1, hours[0]).strftime("%-I %p"),
                    datetime.datetime(2000, 1, 1, hours[-1]).strftime("%-I %p")
                                 )
        else:
            for h in hours:
                tlimit += "%s," % (
                    datetime.datetime(2000, 1, 1, h).strftime("%-I %p"),)
    if len(months) < 12:
        for h in months:
            tlimit += "%s," % (datetime.datetime(2000, h, 1).strftime("%b"),)
    label = """[%s] %s%s
Windrose Plot [%s]
Period of Record: %s - %s""" % (
        station, sname if sname is not None else "((%s))" % (station, ),
        "" if level is None else " @%s hPa" % (level, ),
        tlimit,
        minvalid.strftime("%d %b %Y"), maxvalid.strftime("%d %b %Y"))
    plt.gcf().text(0.14, 0.99, label, va='top')
    plt.gcf().text(0.96, 0.11, (
        "Stats\nn: %s\nCalm: %.1f%%\nAvg Speed: %.1f %s"
        ) % (np.shape(sknt)[0],
             np.sum(np.where(sknt < 2., 1., 0.)) / np.shape(sknt)[0] * 100.,
             np.average(sknt), wu['abbr']), ha='right')
    plt.gcf().text(0.01, 0.11, "Generated: %s" % (
                   datetime.datetime.now().strftime("%d %b %Y"),),
                   verticalalignment="bottom")
    # Make a logo
    im = mpimage.imread('%s/%s' % (DATADIR, 'logo.png'))

    plt.figimage(im, 10, 625)

    return fig
예제 #19
0
파일: ua_windrose.py 프로젝트: akrherz/DEV
    count[mo] += 1
    sped[mo].append( ss )
    drct[mo].append( dd )
print east, count
fig = plt.figure(figsize=(12, 10), dpi=80, facecolor='w', edgecolor='w')
i = 0
months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT',
          'NOV','DEC']
fig.text(0.5,0.96, "1960-2013 Omaha RAOB 200 hPa Monthly Wind Roses", ha='center', va='top', fontsize=26)
fig.text(0.98,0.01, "Percentages shown are frequency of primarily easterly wind",
     ha='right')
for y in [0.65,0.35,0.05]:
    for x in [0.02,0.27,0.52,0.77]:
        ax = WindroseAxes(fig, [x,y,0.21,0.28], axisbg='w')
        fig.add_axes(ax)
        ax.bar(drct[i], sped[i], normed=True, bins=[0,1,20,40,60,80,100,200], 
           opening=0.8, edgecolor='white', nsector=16, rmax=30.0)
        ax.text(0.5,0.25, "%s\n%.1f%%" % (months[i],
		east[i] / float(count[i]) * 100.0), transform=ax.transAxes, fontsize=26)
        i += 1

handles = []
for p in ax.patches_list:
    color = p.get_facecolor()
    handles.append( Rectangle((0, 0), 0.1, 0.3,
                    facecolor=color, edgecolor='black'))

l = fig.legend( handles, ['0-20','20-40','40-60','60-80', '80-100','100+'] , 
     loc=3,
     ncol=6, title='Wind Speed [%s]' % ('mph',),
     mode=None, columnspacing=0.9, handletextpad=0.45)
예제 #20
0
wdir_b[wdir_b == 'nan'] = np.nan
wspd_b[wspd_b == 0] = np.nan
wdir_b[wspd_b == 0] = np.nan
indices = np.logical_not(np.logical_or(np.isnan(wspd_b), np.isnan(wdir_b)))
WS_b = wspd_b[indices]
WD_b = wdir_b[indices]

fig = plt.figure(figsize=[14, 6])
rect = [0, 0, 0.5, 1]
ax = WindroseAxes(fig, rect)
fig.add_axes(ax)

#ax = WindroseAxes.from_ax()
ax.bar(WD,
       WS,
       cmap=cm.viridis,
       normed=True,
       nsector=36,
       bins=np.arange(0, 14, 2))  #summer
plt.text(-0.06,
         1,
         '(a)',
         ha='left',
         va='center',
         transform=ax.transAxes,
         fontsize=bx_fs + 3)
plt.tick_params(axis='x', which='major', labelsize=tk_fs + 3)

ax.set_rlabel_position(340)  #122, 344, 198, 340
ax.set_rmax(10)  #8, 10
ax.set_rticks(np.arange(0, 11, 2))
ax.set_yticklabels(['', '  2%', '  4%', '  6%', '  8%', '  10%'],
예제 #21
0
         "1960-2013 Omaha RAOB 200 hPa Monthly Wind Roses",
         ha='center',
         va='top',
         fontsize=26)
fig.text(0.98,
         0.01,
         "Percentages shown are frequency of primarily easterly wind",
         ha='right')
for y in [0.65, 0.35, 0.05]:
    for x in [0.02, 0.27, 0.52, 0.77]:
        ax = WindroseAxes(fig, [x, y, 0.21, 0.28], axisbg='w')
        fig.add_axes(ax)
        ax.bar(drct[i],
               sped[i],
               normed=True,
               bins=[0, 1, 20, 40, 60, 80, 100, 200],
               opening=0.8,
               edgecolor='white',
               nsector=16,
               rmax=30.0)
        ax.text(0.5,
                0.25,
                "%s\n%.1f%%" % (months[i], east[i] / float(count[i]) * 100.0),
                transform=ax.transAxes,
                fontsize=26)
        i += 1

handles = []
for p in ax.patches_list:
    color = p.get_facecolor()
    handles.append(
        Rectangle((0, 0), 0.1, 0.3, facecolor=color, edgecolor='black'))
예제 #22
0
파일: p16.py 프로젝트: raprasad/iem
def plotter( fdict ):
    """ Go """
    ASOS = psycopg2.connect(database='asos', host='iemdb', user='******')
    cursor = ASOS.cursor(cursor_factory=psycopg2.extras.DictCursor)

    station = fdict.get('zstation', 'AMW')
    network = fdict.get('network', 'IA_ASOS')
    threshold = int(fdict.get('threshold', 80))
    opt = fdict.get('opt', 'ts')
    month = fdict.get('month', 'all')
    nt = NetworkTable(network)

    if month == 'all':
        months = range(1,13)    
    elif month == 'fall':
        months = [9,10,11]
    elif month == 'winter':
        months = [12,1,2]
    elif month == 'spring':
        months = [3,4,5]
    elif month == 'summer':
        months = [6,7,8]
    else:
        ts = datetime.datetime.strptime("2000-"+month+"-01", '%Y-%b-%d')
        # make sure it is length two for the trick below in SQL
        months = [ts.month, 999]

    limiter = "presentwx ~* 'TS'"
    title = "Thunderstorm (TS) contained in METAR"
    if opt == 'tmpf_above':
        limiter = "round(tmpf::numeric,0) >= %s" % (threshold,)
        title = "Air Temp at or above %s$^\circ$F" % (threshold,)
    elif opt == 'tmpf_below':
        limiter = "round(tmpf::numeric,0) < %s" % (threshold,)
        title = "Air Temp below %s$^\circ$F" % (threshold,)
    elif opt == 'dwpf_below':
        limiter = "round(dwpf::numeric,0) < %s" % (threshold,)
        title = "Dew Point below %s$^\circ$F" % (threshold,)
    elif opt == 'dwpf_above':
        limiter = "round(tmpf::numeric,0) >= %s" % (threshold,)
        title = "Dew Point at or above %s$^\circ$F" % (threshold,)

    cursor.execute("""
     SELECT valid, drct, sknt from alldata where station = %s and 
     """+limiter+""" and sknt > 0 and drct >= 0 and drct <= 360
     and extract(month from valid) in %s
    """, (station, tuple(months)))
    sped = []
    drct = [] 
    for i, row in enumerate(cursor):
        if i == 0:
            minvalid = row[0]
            maxvalid = row[0]
        if row[0] < minvalid: minvalid = row[0]
        if row[0] > maxvalid: maxvalid = row[0]
        sped.append( row[2] * 1.15)
        drct.append( row[1] )

        
    fig = plt.figure(figsize=(6, 7), facecolor='w', edgecolor='w')
    rect = [0.1, 0.09, 0.8, 0.8]
    ax = WindroseAxes(fig, rect, axisbg='w')
    fig.add_axes(ax)
    ax.bar(drct, sped, normed=True, bins=[0,2,5,7,10,15,20], opening=0.8, 
           edgecolor='white', nsector=18)
    handles = []
    for p in ax.patches_list:
        color = p.get_facecolor()
        handles.append( Rectangle((0, 0), 0.1, 0.3,
                    facecolor=color, edgecolor='black'))
    l = fig.legend( handles, ('2-5','5-7','7-10','10-15','15-20','20+') , loc=3,
     ncol=6, title='Wind Speed [%s]' % ('mph',), 
     mode=None, columnspacing=0.9, handletextpad=0.45)
    plt.setp(l.get_texts(), fontsize=10)
    
    plt.gcf().text(0.5,0.99, ("%s-%s %s Wind Rose, month=%s\n%s\nWhen  "
                              +"%s") % (minvalid.year,
                            maxvalid.year, station, month.upper(),
                            nt.sts[station]['name'],
                            title ), 
                   fontsize=16, ha='center', va='top')
    plt.gcf().text(0.01, 0.1, "Generated: 8 September 2014" ,
                       verticalalignment="bottom")
    plt.gcf().text(0.95, 0.1, "n=%s" % (len(drct),) ,
                       verticalalignment="bottom", ha='right')


    return fig
예제 #23
0
파일: p16.py 프로젝트: muthulatha/iem
def plotter(fdict):
    """ Go """
    import matplotlib
    matplotlib.use('agg')
    import matplotlib.pyplot as plt
    from windrose import WindroseAxes
    from matplotlib.patches import Rectangle
    pgconn = psycopg2.connect(database='asos', host='iemdb', user='******')

    station = fdict.get('zstation', 'AMW')
    network = fdict.get('network', 'IA_ASOS')
    threshold = int(fdict.get('threshold', 80))
    opt = fdict.get('opt', 'ts')
    month = fdict.get('month', 'all')
    nt = NetworkTable(network)

    if month == 'all':
        months = range(1, 13)
    elif month == 'fall':
        months = [9, 10, 11]
    elif month == 'winter':
        months = [12, 1, 2]
    elif month == 'spring':
        months = [3, 4, 5]
    elif month == 'summer':
        months = [6, 7, 8]
    else:
        ts = datetime.datetime.strptime("2000-"+month+"-01", '%Y-%b-%d')
        # make sure it is length two for the trick below in SQL
        months = [ts.month, 999]

    limiter = "presentwx ~* 'TS'"
    title = "Thunderstorm (TS) contained in METAR"
    if opt == 'tmpf_above':
        limiter = "round(tmpf::numeric,0) >= %s" % (threshold,)
        title = "Air Temp at or above %s$^\circ$F" % (threshold,)
    elif opt == 'tmpf_below':
        limiter = "round(tmpf::numeric,0) < %s" % (threshold,)
        title = "Air Temp below %s$^\circ$F" % (threshold,)
    elif opt == 'dwpf_below':
        limiter = "round(dwpf::numeric,0) < %s" % (threshold,)
        title = "Dew Point below %s$^\circ$F" % (threshold,)
    elif opt == 'dwpf_above':
        limiter = "round(tmpf::numeric,0) >= %s" % (threshold,)
        title = "Dew Point at or above %s$^\circ$F" % (threshold,)

    df = read_sql("""
     SELECT valid, drct, sknt * 1.15 as smph from alldata
     where station = %s and
     """+limiter+""" and sknt > 0 and drct >= 0 and drct <= 360
     and extract(month from valid) in %s
    """, pgconn, params=(station, tuple(months)), index_col='valid')
    minvalid = df.index.min()
    maxvalid = df.index.max()

    fig = plt.figure(figsize=(6, 7.2), facecolor='w', edgecolor='w')
    rect = [0.08, 0.1, 0.8, 0.8]
    ax = WindroseAxes(fig, rect, axisbg='w')
    fig.add_axes(ax)
    ax.bar(df['drct'].values, df['smph'].values,
           normed=True, bins=[0, 2, 5, 7, 10, 15, 20], opening=0.8,
           edgecolor='white', nsector=18)
    handles = []
    for p in ax.patches_list:
        color = p.get_facecolor()
        handles.append(Rectangle((0, 0), 0.1, 0.3,
                                 facecolor=color, edgecolor='black'))
    l = fig.legend(handles,
                   ('2-5', '5-7', '7-10', '10-15', '15-20', '20+'),
                   loc=(0.01, 0.03), ncol=6,
                   title='Wind Speed [%s]' % ('mph',),
                   mode=None, columnspacing=0.9, handletextpad=0.45)
    plt.setp(l.get_texts(), fontsize=10)

    plt.gcf().text(0.5, 0.99,
                   ("%s-%s %s Wind Rose, month=%s\n%s\nWhen  "
                    "%s") % (minvalid.year,
                             maxvalid.year, station, month.upper(),
                             nt.sts[station]['name'],
                             title),
                   fontsize=16, ha='center', va='top')
    plt.gcf().text(0.95, 0.12, "n=%s" % (len(df.index),),
                   verticalalignment="bottom", ha='right')

    return fig, df
예제 #24
0
def _make_plot(station, df, units, nsector, rmax, hours, months, sname, level,
               bins):
    """Generate a matplotlib windrose plot

    Args:
      station (str): station identifier
      df (pd.DataFrame): observations
      drct (list): list of wind directions
      units (str): units of wind speed
      nsector (int): number of bins to use for windrose
      rmax (float): radius of the plot
      hours (list): hour limit for plot
      month (list): month limit for plot
      sname (str): station name
      level (int): RAOB level in hPa of interest
      bins (list): values for binning the wind speeds

    Returns:
      matplotlib.Figure
    """
    # Generate figure
    fig = plt.figure(figsize=(8, 8), dpi=100, facecolor='w', edgecolor='w')
    rect = [0.15, 0.15, 0.7, 0.7]
    ax = WindroseAxes(fig, rect, facecolor='w', rmax=rmax)
    fig.add_axes(ax)
    wu = WINDUNITS[units] if level is None else RAOB_WINDUNITS[units]
    if bins:
        wu['bins'] = bins
        wu['binlbl'] = []
        for i, mybin in enumerate(bins[1:-1]):
            wu['binlbl'].append("%g-%g" % (mybin, bins[i + 2]))
        wu['binlbl'].append("%g+" % (bins[-1], ))
    # Filters the missing values
    df2 = df[df['drct'] >= 0]
    try:
        # Unsure why this bombs out sometimes
        ax.bar(df2['drct'].values,
               df2['speed'].values,
               normed=True,
               bins=wu['bins'],
               opening=0.8,
               edgecolor='white',
               nsector=nsector)
    except Exception as exp:
        pass
    handles = []
    for p in ax.patches_list:
        color = p.get_facecolor()
        handles.append(
            plt.Rectangle((0, 0), 0.1, 0.3, facecolor=color,
                          edgecolor='black'))
    l = fig.legend(handles,
                   wu['binlbl'],
                   bbox_to_anchor=(0.01, 0.01, 0.98, 0.09),
                   loc='center',
                   ncol=6,
                   title='Wind Speed [%s]' % (wu['abbr'], ),
                   mode=None,
                   columnspacing=0.9,
                   handletextpad=0.45,
                   fontsize=14)
    plt.setp(l.get_texts(), fontsize=10)
    # Now we put some fancy debugging info on the plot
    tlimit = "Time Domain: "
    if len(hours) == 24 and len(months) == 12:
        tlimit = "All Year"
    if len(hours) < 24:
        if len(hours) > 4:
            tlimit += "%s-%s" % (
                datetime.datetime(2000, 1, 1, hours[0]).strftime("%-I %p"),
                datetime.datetime(2000, 1, 1, hours[-1]).strftime("%-I %p"))
        else:
            for h in hours:
                tlimit += "%s," % (datetime.datetime(2000, 1, 1,
                                                     h).strftime("%-I %p"), )
    if len(months) < 12:
        for h in months:
            tlimit += "%s," % (datetime.datetime(2000, h, 1).strftime("%b"), )
    label = """[%s] %s%s
Windrose Plot [%s]
Period of Record: %s - %s""" % (
        station, sname if sname is not None else "((%s))" %
        (station, ), "" if level is None else " @%s hPa" %
        (level, ), tlimit, df['valid'].min().strftime("%d %b %Y"),
        df['valid'].max().strftime("%d %b %Y"))
    plt.gcf().text(0.14, 0.99, label, va='top', fontsize=14)
    plt.gcf().text(
        0.96,
        0.11,
        ("Summary\nn: %s\nMissing: %s\nCalm: %.1f%%\nAvg Speed: %.1f %s") %
        (len(df.index), len(df.index) - len(df2.index),
         len(df[df['sknt'] == 0].index) / float(len(df2.index)) * 100.,
         df['speed'].mean(), wu['abbr']),
        ha='right',
        fontsize=14)
    plt.gcf().text(0.01,
                   0.11,
                   "Generated: %s" %
                   (datetime.datetime.now().strftime("%d %b %Y"), ),
                   verticalalignment="bottom",
                   fontsize=14)
    # Make a logo
    im = mpimage.imread('%s/%s' % (DATADIR, 'logo.png'))
    plt.figimage(im, 10, 735)

    return fig
예제 #25
0
left_rectangle = [
    0, 0.1, 0.4, 0.75
]  # [left, bottom, width, height] as a fraction of total figure size
ax1 = fig.add_axes(left_rectangle)  # creates the axes of specified dimensions

mto[wsp].hist(bins=100)
ax1.set_xscale("log")
ax1.set_xlabel("wind speed (m/s)")

right_rectangle = [0.5, 0.1, 0.5, 0.75]  # [left, bottom, width, height]
ax = WindroseAxes(fig, right_rectangle)
fig.add_axes(ax)
ax.bar(mto[wdir],
       mto[wsp],
       normed=True,
       opening=0.8,
       edgecolor='white',
       bins=np.logspace(-1, 1, 10))
ax.set_title("annual", position=(0.5, 1.1))

ax.set_legend()
ax.legend(title="wind speed (m/s)", loc=(1.1, 0))

######################################################################
# The numbers around the radar plot indicate frequencies for the given
# direction. They look quite ugly, and would benefit from some formatting.
# which is not super trivial:
#

from windrose import WindroseAxes