Пример #1
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() 
Пример #2
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']
Пример #3
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()    
Пример #4
0
def main(filename):
    fig = plt.figure(figsize=(12, 8), dpi=80, facecolor='w', edgecolor='w')
    ax = WindroseAxes(fig, [0.1, 0.1, 0.8, 0.8], facecolor='w')
    fig.add_axes(ax)
    windRose = np.loadtxt(filename)
    indexes = np.where(windRose[:, 1] > 0.1)
    windDirections = windRose[indexes[0], 0]
    windSpeeds = windRose[indexes[0], 1]
    # windSpeeds = windRose[indexes[0], 1] * 2 / np.sqrt(np.pi)  # convert from mean wind speed to weibull scale factor
    windFrequencies = windRose[indexes[0], 2]
    # size = len(windDirections)
    ax.box(windDirections, windSpeeds, frequency=windFrequencies, mean_values=1, bins=[15, 18, 20, 23, 25], nsector=72)
    # ax.box(windDirections, [[windSpeeds[i], 2] for i in range(len(windSpeeds))], frequency=windFrequencies, weibull_factors=1, bins=[15, 18, 20, 23, 25], nsector=72)
    ax.set_yticklabels([])
    plt.show()
Пример #5
0
    def plot_wind_rose_at_cities(self,datatype=['UINT','VINT']):
        """ plot wind rose at each city based on cities['city']['UINT'] and ['VINT']"""
        from windrose import WindroseAxes
        from matplotlib import pyplot as plt
        import matplotlib.cm as cm
        import numpy as np

        #fig, ax = plt.subplots(5,2,sharex=True)
        #plt_idx=0
        for city,var in self.cities.iteritems():
            # convert all the u and v into one array
            u_int=np.concatenate([ var[datatype[0]][i] for i,b in var[datatype[0]].iteritems()])
            v_int=np.concatenate([ var[datatype[1]][i] for i,b in var[datatype[1]].iteritems()])
            # http://stackoverflow.com/questions/21484558/how-to-calculate-wind-direction-from-u-and-v-wind-components-in-r
            # get from u v to windrose
            wind_abs=np.sqrt(np.power(u_int,2.0)+np.power(v_int,2.0))
            wind_dir_trig_to = np.arctan2(u_int/wind_abs,v_int/wind_abs)
            wind_dir_trig_to_degrees = wind_dir_trig_to * 180.0/np.pi  
            wind_dir_trig_from_degrees = wind_dir_trig_to_degrees + 180.0
            wind_dir_cardinal = 90 - wind_dir_trig_from_degrees

            # draw wind rose

            ax = WindroseAxes.from_ax()
            ax.bar(wind_dir_trig_from_degrees, wind_abs, normed=True, opening=0.8, edgecolor='white')
            #ax.bar(wind_dir_cardinal, wind_abs, normed=True, opening=0.8, edgecolor='white')
            ax.set_legend()
            ax.set_title(city)
            #plt_idx+=1

            #plt.show(block=False)
            #savefig('foo.png')
            fname='windrose_'+datatype[0]+datatype[1]+'_'+city+'.png'
            plt.savefig(fname,format='png',dpi=300)
Пример #6
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
Пример #7
0
def show_wind_rose(data_tuples):

    ws = [(lambda x: x[3])(var) for var in data_tuples]

    wd = [(lambda x: x[4])(var) for var in data_tuples]

    ax = WindroseAxes.from_ax()

    ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')

    ax.set_legend()

    plt.show()
Пример #8
0
def main():
    df_all = pd.read_csv("samples/sample_wind_poitiers.csv", parse_dates=['Timestamp'])
    df_all = df_all.set_index('Timestamp')

    f_year = get_by_func('year')
    df_all['by_page'] = df_all.index.map(f_year)
    f_month = get_by_func('month')
    df_all['by'] = df_all.index.map(f_month)

    df_all = df_all.reset_index().set_index(['by_page', 'by', 'Timestamp'])

    print(df_all)

    year = 2014

    nrows, ncols = 3, 4
    margin_pct = 0.1
    margin_pct_x, margin_pct_y = margin_pct, margin_pct
    width, height = (1.0 - margin_pct_x) / ncols, (1.0 - margin_pct_y) / nrows

    for month in range(1, 13):
        df = df_all.loc[year].loc[(year, month)]
        i_sheet, i_row, i_col = tuple_position(month - 1, nrows, ncols)
        assert i_sheet == 0
        bins = np.arange(0.01, 8, 1)
        direction = df['direction'].values
        var = df['speed'].values

        fig = plt.gcf()
        rect = [i_col * width + margin_pct_x / 2, 1 - (i_row + 1) * height - margin_pct_y / 2, width, height]  # [left, bottom, width, height]
        ax = WindroseAxes(fig, rect, rmax=1000)
        # ax.set_title(month)
        fig.add_axes(ax)
        # ax.contour(direction, var, bins=bins, colors='black', lw=3)
        ax.contourf(direction, var, bins=bins, cmap=cm.hot)
        ax.contour(direction, var, bins=bins, colors='black')

    plt.show()
Пример #9
0
def test_windrose_np_mpl_oo():
    bins = np.arange(0, 8, 1)

    #windrose with scatter plot
    ax = WindroseAxes.from_ax()
    ax.scatter(wd, ws, alpha=0.2)
    ax.set_legend()
    plt.savefig('tests/output/oo/scatter.png')

    #windrose like a stacked histogram with normed (displayed in percent) results
    ax = WindroseAxes.from_ax()
    ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')
    ax.set_legend()
    plt.savefig('tests/output/oo/bar.png')

    #Another stacked histogram representation, not normed, with bins limits
    ax = WindroseAxes.from_ax()
    ax.box(wd, ws, bins=bins)
    ax.set_legend()
    plt.savefig('tests/output/oo/box.png')

    #A windrose in filled representation, with a controled colormap
    ax = WindroseAxes.from_ax()
    ax.contourf(wd, ws, bins=bins, cmap=cm.hot)
    ax.set_legend()
    plt.savefig('tests/output/oo/contourf.png')

    #Same as above, but with contours over each filled region...
    ax = WindroseAxes.from_ax()
    ax.contourf(wd, ws, bins=bins, cmap=cm.hot)
    ax.contour(wd, ws, bins=bins, colors='black')
    ax.set_legend()
    plt.savefig('tests/output/oo/contourf-contour.png')

    #...or without filled regions
    ax = WindroseAxes.from_ax()
    ax.contour(wd, ws, bins=bins, cmap=cm.hot, lw=3)
    ax.set_legend()
    plt.savefig('tests/output/oo/contour.png')

    #print ax._info
    #plt.show()

    ax = WindAxes.from_ax()
    bins = bins[1:]
    ax.pdf(ws, bins=bins)
    plt.savefig('tests/output/oo/pdf.png')
Пример #10
0
def main():
    # Create wind speed and direction variables
    N = 500
    ws = np.random.random(N) * 6
    wd = np.random.random(N) * 360

    ax = WindroseAxes.from_ax()
    ax.scatter(wd, ws, alpha=0.2)
    ax.set_legend()

    # windrose like a stacked histogram with normed (displayed in percent) results
    ax = WindroseAxes.from_ax()
    ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')
    ax.set_legend()

    # Another stacked histogram representation, not normed, with bins limits
    ax = WindroseAxes.from_ax()
    bins = np.arange(0, 8, 1)
    ax.box(wd, ws, bins=bins)
    ax.set_legend()

    # A windrose in filled representation, with a controled colormap
    ax = WindroseAxes.from_ax()
    ax.contourf(wd, ws, bins=bins, cmap=cm.hot)
    ax.set_legend()

    # Same as above, but with contours over each filled region...
    ax = WindroseAxes.from_ax()
    ax.contourf(wd, ws, bins=bins, cmap=cm.hot)
    ax.contour(wd, ws, bins=bins, colors='black')
    ax.set_legend()

    # ...or without filled regions
    ax = WindroseAxes.from_ax()
    ax.contour(wd, ws, bins=bins, cmap=cm.hot, lw=3)
    ax.set_legend()

    # print ax._info
    # plt.show()

    ax = WindAxes.from_ax()
    bins = np.arange(0, 6 + 1, 0.5)
    bins = bins[1:]
    ax.pdf(ws, bins=bins)
    plt.show()
Пример #11
0
def windrose(self,
             season_period="Annual",
             day_period="Daily",
             n_sector=16,
             cmap=None,
             tone_color="k",
             save=False):

    # Construct the save_path and create directory if it doesn't exist
    save_path = self.file_path.parent / "{}_Plot".format(
        self.file_path.stem) / "wind_rose_{}{}.png".format(
            season_period, day_period)

    # Describe a set of masks to remove unwanted hours of the year
    speed_mask = (self.wind_speed != 0)
    direction_mask = (self.wind_direction != 0)
    mask = np.array([
        time_of_year_mask[day_period], time_of_year_mask[season_period],
        speed_mask, direction_mask
    ]).all(axis=0)

    fig = plt.figure(figsize=(6, 6))
    ax = WindroseAxes.from_ax()
    ax.bar(self.wind_direction[mask],
           self.wind_speed[mask],
           normed=True,
           bins=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
           opening=0.95,
           edgecolor='White',
           lw=0.1,
           nsector=n_sector,
           cmap=cm.get_cmap('GnBu') if cmap is None else cm.get_cmap(cmap))

    lgd = ax.legend(bbox_to_anchor=(1.1, 0.5),
                    loc='center left',
                    frameon=False,
                    title="m/s")
    lgd.get_frame().set_facecolor((1, 1, 1, 0))
    [plt.setp(text, color=tone_color) for text in lgd.get_texts()]
    plt.setp(lgd.get_title(), color=tone_color)

    for i, leg in enumerate(lgd.get_texts()):
        b = leg.get_text().replace('[', '').replace(')', '').split(' : ')
        lgd.get_texts()[i].set_text(b[0] + ' to ' + b[1])

    ax.grid(linestyle=':', color=tone_color, alpha=0.5)
    ax.spines['polar'].set_visible(False)
    plt.setp(ax.get_xticklabels(), color=tone_color)
    plt.setp(ax.get_yticklabels(), color=tone_color)
    ax.set_title("{} - {}\n{} - {} - {}".format(season_period, day_period,
                                                self.city, self.country,
                                                self.station_id),
                 y=1.06,
                 color=tone_color,
                 loc="center",
                 va="bottom",
                 ha="center",
                 fontsize="medium")

    plt.tight_layout()

    # Save figure
    if save:
        save_path.parent.mkdir(parents=True, exist_ok=True)
        plt.savefig(save_path,
                    bbox_extra_artists=(lgd, ),
                    bbox_inches='tight',
                    dpi=300,
                    transparent=False)
        print("Windrose saved to {}".format(save_path))

    plt.close()

    return fig
Пример #12
0
def rose_fig(metdat,
             catinfo,
             category=None,
             vertloc=80,
             bins=6,
             nsector=36,
             ylim=None,
             noleg=False):
    """**Get Wind Rose Figure**.

    Plot the 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)
    winddir = metdat[dircol]
    var = metdat[varcol]

    # 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])

    # built figure
    fig = plt.figure()
    ax = WindroseAxes.from_ax(fig=fig)
    ax.bar(winddir,
           var,
           normed=True,
           opening=0.95,
           edgecolor='white',
           bins=bins,
           nsector=nsector,
           colors=colors,
           linewidth=0.35)

    # legend
    leg = ['blank']
    if noleg is not True:
        leg = ax.set_legend(loc=7,
                            bbox_to_anchor=(1.55, 0.5),
                            fontsize=10,
                            frameon=False)
        # add labels to legend
        leg.set_title(catinfo['labels'][category])
        fig.text(0.875, 0.275, r'$z={}$ m'.format(vertloc))

    # adjust plot for specified max frequency
    if ylim is None:
        ylim = ax.get_ylim()[-1]

    # frequency axis limits and labels
    ax.set_ylim(0, ylim)
    ax.set_yticks(np.linspace(0, ylim, 4))
    ax.set_yticklabels([str(round(x, 1)) for x in np.linspace(0, ylim, 4)])

    return fig, ax, leg
Пример #13
0
    def refresh_plot(self, data, File, Var):

        with plt.style.context("cyberpunk"):

            self.rmmpl()
            self.addmpl()

            self.sc.fig1.clf()

            ax1f1 = self.sc.fig1.add_subplot(111)

            index_name0 = None
            for i, file in enumerate(File):
                for var in Var[i]:
                    scl_fac = data[file]['metadata'][var]['scale_factor']
                    add_offset = data[file]['metadata'][var]['add_offset']
                    index_name = data[file]['dataframe'].index.name
                    if index_name0:
                        if index_name0 != index_name:
                            display_warning('Variables doesn'
                                            't have the same index')
                            continue

                    x = data[file]['dataframe'].index
                    y = ((data[file]['dataframe'][var]) * scl_fac) + add_offset

                    if hasattr(self.plot_name, 'currentText'):
                        plot_name = str(self.plot_name.currentText())
                    else:
                        plot_name = 'plot'

                    if isinstance(x, pd.MultiIndex):
                        plot_name = 'pcolor'

                    if 'hist' == plot_name:
                        # the histogram of the data
                        ax1f1.hist(y, density=1)
                        self.add_metadata(
                            ax1f1,
                            Xmetadata=data[file]['metadata'][var],
                            Ymetadata=None)
                    elif 'pcolor' == plot_name:
                        indexes = data[file]['dataframe'].index.names
                        X = data[file]['dataframe'].unstack()[indexes[0]]
                        Y = data[file]['dataframe'].unstack()[
                            indexes[1]].values
                        Z = data[file]['dataframe'].unstack()[var].values
                        ax1f1.set_gid('ax')
                        cf = ax1f1.pcolormesh(date2num(X), Y, Z)
                        locator = AutoDateLocator()
                        date_format = AutoDateFormatter(locator)
                        ax1f1.xaxis.set_major_formatter(date_format)
                        self.sc.fig1.autofmt_xdate()
                        self.sc.fig1.colorbar(cf, ax=ax1f1)
                        self.add_metadata(
                            ax1f1,
                            Xmetadata=data[file]['metadata'][indexes[0]],
                            Ymetadata=data[file]['metadata'][indexes[1]],
                            legend=False)
                    elif 'progressif' == plot_name:
                        if index_name == 'time':
                            display_error('Index can not be time')
                            continue
                        X = x.array
                        Y = y.array
                        innX = np.isnan(X)
                        innY = np.isnan(Y)

                        X[innX] = 0
                        Y[innY] = 0

                        posX = np.cumsum(X)
                        posY = np.cumsum(Y)
                        posX[innX] = np.NaN
                        posY[innY] = np.NaN
                        ax1f1.quiver(posX, posY, X, Y)

                        self.add_metadata(ax1f1,
                                          data[file]['metadata'][index_name],
                                          data[file]['metadata'][var],
                                          legend=False)
                    elif 'rose' == plot_name:
                        if index_name == 'time':
                            display_error(
                                'Index can not be time,must be direction or V')
                            continue

                        self.sc.fig1.clf()
                        ax = WindroseAxes.from_ax(fig=self.sc.fig1)
                        gd_data = ~np.isnan(y) | ~np.isnan(x)
                        y = y[gd_data]
                        x = x[gd_data]

                        if any(x < 0):  # it is U and V
                            y, x = uv2spdir(y.values, x.values)
                        ax.bar(x,
                               y,
                               normed=True,
                               opening=0.8,
                               edgecolor='white')
                        ax.set_legend(
                            units=data[file]['metadata'][var]['units'])

                    else:
                        ax1f1.set_gid('ax')
                        plot_ft = getattr(ax1f1, plot_name)
                        if not check_timeseries(y.values):
                            typ = '-'
                        else:
                            typ = '+'
                        plot_ft(x,
                                y,
                                typ,
                                label=var,
                                gid=file + ';' + var,
                                linewidth=0.8)
                        #ax1f1.set_xlim(x[0],x[-1])

                        self.add_metadata(ax1f1,
                                          data[file]['metadata'][index_name],
                                          data[file]['metadata'][var])
                        if index_name == 'time':
                            self.sc.fig1.autofmt_xdate()

                        ax1f1.grid(True)
                    index_name0 = copy.deepcopy(index_name)
Пример #14
0
def _make_plot(station, df, units, nsector, rmax, hours, months, sname, level,
               bins, **kwargs):
    """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.12, 0.12, 0.76, 0.76]
    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:
        sys.stderr.write(str(exp))
    # Figure out the shortest bar
    mindir = ax._info['dir'][np.argmin(np.sum(ax._info['table'], axis=0))]
    ax.set_rlabel_position((450 - mindir) % 360 - 15)
    # Adjust the limits so to get a empty center
    rmin, rmax = ax.get_ylim()
    ax.set_rorigin(0 - (rmax - rmin) * 0.2)
    # Make labels have % formatters
    ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f%%'))

    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'))
    legend = 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(legend.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.5,
        0.5,
        "Calm\n%.1f%%" %
        (len(df[df['sknt'] == 0].index) / float(len(df2.index)) * 100., ),
        ha='center',
        va='center',
        fontsize=14)
    plt.gcf().text(
        0.96,
        0.11, ("Summary\nobs count: %s\nMissing: %s\nAvg Speed: %.1f %s") %
        (len(df.index), len(df.index) - len(df2.index), df['speed'].mean(),
         wu['abbr']),
        ha='right',
        fontsize=14)
    if not kwargs.get('nogenerated', False):
        plt.gcf().text(0.02,
                       0.1,
                       "Generated: %s" %
                       (datetime.datetime.now().strftime("%d %b %Y"), ),
                       verticalalignment="bottom",
                       fontsize=14)
    # Denote the direction blowing from
    plt.gcf().text(0.02,
                   0.125,
                   "Direction is where the wind is\nblowing from, not toward.",
                   va='bottom')
    # Make a logo
    im = mpimage.imread('%s/%s' % (DATADIR, 'logo.png'))
    plt.figimage(im, 10, 735)

    return fig
Пример #15
0
def main(filename, exit_at, size, offset, dpi, figsize, fps, bins_min,
         bins_max, bins_step, fontname, filename_out):
    # convert figsize (string like "8,9" to a list of float [8.0, 9.0]
    figsize = figsize.split(",")
    figsize = map(float, figsize)

    # Read CSV file to a Pandas DataFrame
    df_all = pd.read_csv(filename)
    df_all['Timestamp'] = pd.to_datetime(df_all['Timestamp'])
    df_all = df_all.set_index('Timestamp')
    #df_all = df_all.iloc[-10000:,:]
    df_all.index = df_all.index.tz_localize('UTC').tz_convert('UTC')

    # Get Numpy arrays from DataFrame
    direction_all = df_all['direction'].values
    var_all = df_all['speed'].values
    index_all = df_all.index.to_datetime()  #.values -> .to_datetime()

    # Define bins
    bins = np.arange(bins_min, bins_max, bins_step)

    # Create figure
    fig = plt.figure(figsize=figsize, dpi=dpi, facecolor='w', edgecolor='w')

    # Create a video writer (ffmpeg can create MPEG files)
    FFMpegWriter = matplotlib.animation.writers['ffmpeg']
    metadata = dict(title='windrose',
                    artist='windrose',
                    comment="""Made with windrose
http://www.github.com/scls19fr/windrose""")
    writer = FFMpegWriter(fps=fps, metadata=metadata)

    dt0 = index_all[offset]
    print("size: %d" % size)
    print("offset: %d" % offset)
    print("First dt: %s" % dt0)

    print("")

    dt2 = None
    i = 0
    with writer.saving(fig, filename_out, 100):
        #for i in range(1000): # 100
        try:
            while True:  # loop until fails (end of data)
                print("Processing %d" % (i + 1))
                i1 = offset + i * size
                i2 = offset + (i + 1) * size + 1

                index = index_all[i1:i2]
                dt1 = index[0]
                dt2 = index[-1]
                td = dt2 - dt1
                title = "  From %s\n    to %s" % (dt1, dt2)
                print(title)
                print("    td %r" % td)
                #print("    td %r" % td.astype('timedelta64[m]'))

                try:
                    direction = direction_all[i1:i2]
                    var = var_all[i1:i2]

                    ax = WindroseAxes.from_ax(
                        fig=fig)  # scatter, bar, box, contour, contourf

                    #ax.scatter(direction, var, alpha=0.2)
                    #ax.set_xlim([-bins[-1], bins[-1]])
                    #ax.set_ylim([-bins[-1], bins[-1]])

                    #ax.bar(direction, var, bins=bins, normed=True, opening=0.8, edgecolor='white')

                    #ax.box(direction, var, bins=bins)

                    #ax.contour(direction, var, cmap=cm.hot, lw=3, bins=bins)

                    ax.contourf(direction, var, bins=bins, cmap=cm.hot)
                    ax.contour(direction, var, bins=bins, colors='black', lw=3)

                    ax.set_legend()

                    #ax = WindAxes.from_ax(fig=fig) # pdf: probability density function
                    #ax.pdf(var, bins=bins)
                    #ax.set_xlim([0, bins[-1]])
                    #ax.set_ylim([0, 0.4])

                    ax.set_title(title, fontname=fontname)

                    writer.grab_frame()
                except KeyboardInterrupt:
                    return
                except Exception as e:
                    print(traceback.format_exc(), file=sys.stderr)

                print("")

                fig.clf()
                i += 1
                if i == exit_at - 1:  # exit_at must be > 1
                    break
        except KeyboardInterrupt:
            return
        except Exception as e:
            print(traceback.format_exc(), file=sys.stderr)

        print("First dt: %r" % dt0)
        print("Last  dt: %r" % dt2)
        td = dt2 - dt0
        print("      td: %r" % td.astype('timedelta64[D]'))
        N = i + 1
        print("Number of slides: %d" % N)

    #plt.show()

    print("")
    print("Save file to '%s'" % filename_out)
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from windrose import WindroseAxes
from windrose import WindAxes

from matplotlib import pyplot as plt
import matplotlib.cm as cm
import numpy as np

#Create wind speed and direction variables
N = 500
ws = np.random.random(N) * 6
wd = np.random.random(N) * 360

ax = WindroseAxes.from_ax()
ax.scatter(wd, ws, alpha=0.2)
ax.set_legend()

#windrose like a stacked histogram with normed (displayed in percent) results
ax = WindroseAxes.from_ax()
ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')
ax.set_legend()

#Another stacked histogram representation, not normed, with bins limits
ax = WindroseAxes.from_ax()
bins = np.arange(0, 8, 1)
ax.box(wd, ws, bins=bins)
ax.set_legend()

#A windrose in filled representation, with a controled colormap
Пример #17
0
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
Пример #18
0
data = datafile_b.readlines()[1:]
data = np.array([x.split(',') for x in data])
wspd_b = np.array(data[:, 3]).astype(np.float) * 0.514444
wdir_b = np.array(data[:, 2]).astype(np.float)
wspd_b[wspd_b == 'nan'] = np.nan
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,
Пример #19
0
    if dd >= 45 and dd <= 135:
        east[mo] += 1
    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,
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
Пример #21
0
def new_axes(fig, rect):
    ax = WindroseAxes(fig, rect, axisbg='w')
    fig.add_axes(ax)
    return ax
Пример #22
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()
Пример #23
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()
Пример #24
0
 def getPlot(self, params):
     LIST_CITY = [
         "львов+", "кривой_рог+", "симферополь+", "и_франк+", "донецк+",
         "харьков+", "днепропетровськ+", "киев+", "одесса+", "луганськ+"
     ]
     citys = params["city"]
     index = LIST_CITY.index(citys + "+")
     df = pd.read_csv(str(index) + ".csv", index_col=0)
     df = df.set_index(df['UTC'])
     date_f = params["date"].split("-")[0]
     date_s = params["date"].split("-")[1]
     day_f = date_f.split('.')[0]
     mon_f = date_f.split('.')[1]
     day_s = date_s.split('.')[0]
     mon_s = date_s.split('.')[1]
     df = df[(df['UTC'] > '2012-' + mon_f + '-' + day_f)
             & (df['UTC'] < '2012-' + mon_s + '-' + day_s)]
     if params["exer"] == "T_plot":
         del df["FF"]
         del df["N"]
         del df["PPP"]
         del df["hhh"]
         del df["Unnamed: 0.1"]
         plt_obj = df.plot(figsize=(30, 10))
         plt_obj.set_ylabel("Sun Izo")
         plt_obj.set_xlabel("Date")
         plt_obj.set_title(citys)
     elif params["exer"] == "T_val_plot":
         del df["FF"]
         del df["N"]
         del df["PPP"]
         del df["hhh"]
         del df["Unnamed: 0.1"]
         dict_val = {}
         for i in range(-30, 35, 1):
             q = (df['T'] == i).sum()
             dict_val.update({i: q})
         dfc = pd.DataFrame.from_dict(dict_val, orient='index')
         plt_obj = dfc.plot.bar(figsize=(30, 10))
     elif params["exer"] == "sun_izo":
         del df["FF"]
         del df["N"]
         del df["PPP"]
         del df["T"]
         del df["Unnamed: 0.1"]
         plt_obj = df.plot(figsize=(30, 10))
         plt_obj.set_ylabel("Temperature")
         plt_obj.set_xlabel("Date")
         plt_obj.set_title(citys)
     elif params["exer"] == "val_wind":
         del df["T"]
         del df["N"]
         del df["PPP"]
         del df["hhh"]
         del df["Unnamed: 0.1"]
         dict_val = {}
         for i in range(0, 15, 1):
             q = (df['FF'] == i).sum()
             dict_val.update({i: q})
         dfc = pd.DataFrame.from_dict(dict_val, orient='index')
         plt_obj = dfc.plot.bar(figsize=(30, 10))
         plt_obj.set_ylabel("Wind")
         plt_obj.set_xlabel("Num")
         plt_obj.set_title(citys)
     elif params["exer"] == "val_sun_izo":
         arr = df["hhh"].unique()
         del df["FF"]
         del df["N"]
         del df["PPP"]
         del df["T"]
         del df["Unnamed: 0.1"]
         dict_val = {}
         for i in arr:
             if i == 0:
                 continue
             else:
                 q = (df['hhh'] == i).sum()
                 dict_val.update({i: q})
         dfc = pd.DataFrame.from_dict(dict_val, orient='index')
         plt_obj = dfc.plot.bar(figsize=(30, 10))
     elif params["exer"] == "Wind":
         ws_df = df["dd"].to_numpy()
         wd_df = df["FF"].to_numpy()
         ws = np.random.random(1500) * 6
         wd = np.random.random(1500) * 360
         ax = WindroseAxes.from_ax()
         ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')
         ax.set_legend()
         fig = ax.get_figure()
         return fig
     elif params["exer_2"] == "2_7" or params["exer_2"] == "2_4":
         citys = params["city"]
         index = LIST_CITY.index(citys + "+")
         df = pd.read_csv(str(index) + ".csv", index_col=0)
         q = (df['T'] == params["sli"] - 30).sum()
         res = q * 18.23
         List_str = params["s_s"] + "/" + params["s_s_s"]
         List_arg = List_str.split('/')
         List_arg = list(map(int, List_arg))
         Q_d = List_arg[0] * List_arg[1]
         Q_v = List_arg[3] * List_arg[4]
         Q_td = Q_d * ((List_arg[2] - List_arg[6]) /
                       (List_arg[7] - List_arg[6]))
         Q_tv = Q_v * ((List_arg[5] - List_arg[6]) /
                       (List_arg[7] - List_arg[6]))
         Q_tgv = ((Q_td - Q_tv) / 998.23)
         W_tgv = 1.163 * Q_tgv * (List_arg[8] - List_arg[6])
         if params["exer_2"] == "2_7":
             dict_cost = {
                 "1": 16.784,
                 "2": 12.76,
                 "3": 19.20,
                 "4": 23.20,
                 "5": 17.74,
                 "6": 12.80
             }
             f = int(params["s_six_t"])
             key = params["s_six"]
             List_cost = []
             for i in dict_cost:
                 qu = res * W_tgv * f * dict_cost[i]
                 List_cost.append(qu)
             dict_val = {i: List_cost[i] for i in range(0, len(List_cost))}
             dfc = pd.DataFrame.from_dict(dict_val, orient='index')
             plt_obj = dfc.plot.bar(figsize=(30, 10))
         elif params["exer_2"] == "2_4":
             dict_gr = {}
             for i in range(-20, 20):
                 dict_gr.update({i: i * W_tgv})
             dfc = pd.DataFrame.from_dict(dict_gr, orient='index')
             plt_obj = dfc.plot(figsize=(30, 10), marker=".", markersize=40)
             plt_obj.grid()
     fig = plt_obj.get_figure()
     return fig
Пример #25
0
    def getPlot(self, params):
        plt_obj = None
        LIST_CITY = [
            "львов+", "кривой_рог+", "симферополь+", "и_франк+", "донецк+",
            "харьков+", "днепропетровськ+", "киев+", "одесса+", "луганськ+"
        ]
        cities = params["city"]
        index = LIST_CITY.index(cities + "+")
        df = pd.read_csv(str(index) + ".csv", index_col=0)
        df = df.set_index(df['UTC'])
        date_f = params["date"].split("-")[0]
        date_s = params["date"].split("-")[1]
        day_f = date_f.split('.')[0]
        mon_f = date_f.split('.')[1]
        day_s = date_s.split('.')[0]
        mon_s = date_s.split('.')[1]
        df = df[(df['UTC'] > '2012-' + mon_f + '-' + day_f)
                & (df['UTC'] < '2012-' + mon_s + '-' + day_s)]
        if params["exer"] == "T_plot":
            del df["FF"]
            del df["N"]
            del df["PPP"]
            del df["hhh"]
            del df["Unnamed: 0.1"]
            plt_obj = df.plot(figsize=(30, 10))
            plt_obj.set_ylabel("Sun Izo", fontsize=18)
            plt_obj.set_xlabel("Date", fontsize=18)
            plt_obj.set_title("Температурні умови", fontsize=18)
        elif params["exer"] == "T_val_plot":
            del df["FF"]
            del df["N"]
            del df["PPP"]
            del df["hhh"]
            del df["Unnamed: 0.1"]
            dict_val = {}
            for i in range(-30, 35, 1):
                q = (df['T'] == i).sum()
                dict_val.update({i: q})
            dfc = pd.DataFrame.from_dict(dict_val, orient='index')
            plt_obj = dfc.plot.bar(color='green', figsize=(30, 10))
            plt_obj.set_ylabel("t, год", fontsize=18)
            plt_obj.set_xlabel("T, (°C)", fontsize=18)
            plt.xticks(fontsize=18)
            plt.yticks(fontsize=18)
        elif params["exer"] == "sun_izo":
            del df["FF"]
            del df["N"]
            del df["PPP"]
            del df["T"]
            del df["Unnamed: 0.1"]
            plt_obj = df.plot(figsize=(30, 10))
            plt_obj.set_ylabel("Вт/м²", fontsize=18)
            plt_obj.set_xlabel("Date", fontsize=18)
            plt_obj.set_title("Інтенсивність сонячної інсоляції", fontsize=18)
            plt.xticks(rotation=45, fontsize=18)
            plt.yticks(fontsize=18)
        elif params["exer"] == "val_wind":
            del df["T"]
            del df["N"]
            del df["PPP"]
            del df["hhh"]
            del df["Unnamed: 0.1"]
            dict_val = {}
            for i in range(0, 15, 1):
                q = (df['FF'] == i).sum()
                dict_val.update({i: q})
            dfc = pd.DataFrame.from_dict(dict_val, orient='index')
            plt_obj = dfc.plot.bar(figsize=(30, 10))
            plt_obj.set_ylabel("год", fontsize=18)
            plt_obj.set_xlabel("м/с", fontsize=18)
            plt_obj.set_title(
                'Розподіл вітрового потенціалу за швидкостями, год',
                fontsize=18)
            plt.xticks(fontsize=18)
            plt.yticks(fontsize=18)
        elif params["exer"] == "val_sun_izo":
            arr = df["hhh"].unique()
            del df["FF"]
            del df["N"]
            del df["PPP"]
            del df["T"]
            del df["Unnamed: 0.1"]
            dict_val = {}
            for i in arr:
                if i == 0:
                    continue
                else:
                    q = sum(df["hhh"]) if df['hhh'] == i else 0
                    dict_val.update({i: q})
            dfc = pd.DataFrame.from_dict(dict_val, orient='index')
            plt_obj = dfc.plot.bar(figsize=(30, 10))
            plt_obj.set_xlabel("Вт/м²", fontsize=18)
            plt_obj.set_ylabel("год", fontsize=18)
            plt_obj.set_title("Тривалість режимів сонячної активності",
                              fontsize=18)
            plt.xticks(fontsize=18)
            plt.yticks(fontsize=18)
        elif params["exer"] == "Wind":
            ws_df = df["dd"].to_numpy()
            wd_df = df["FF"].to_numpy()
            ws = np.random.random(1500) * 4
            wd = np.random.random(1500) * 360
            ax = WindroseAxes.from_ax()
            ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')

            ax.set_legend()
            fig = ax.get_figure()
            return fig
        elif params["exer_2"] == "2_7" or params["exer_2"] == "2_4":
            citys = params["city"]
            index = LIST_CITY.index(citys + "+")
            df = pd.read_csv(str(index) + ".csv", index_col=0)
            q = (df['T'] == params["sli"] - 30).sum()
            res = q * 18.23
            List_str = params["s_s"] + "/" + params["s_s_s"]
            List_arg = List_str.split('/')
            List_arg = list(map(int, List_arg))
            Q_d = List_arg[0] * List_arg[1]
            Q_v = List_arg[3] * List_arg[4]
            Q_td = Q_d * ((List_arg[2] - List_arg[6]) /
                          (List_arg[7] - List_arg[6]))
            Q_tv = Q_v * ((List_arg[5] - List_arg[6]) /
                          (List_arg[7] - List_arg[6]))
            Q_tgv = ((Q_td - Q_tv) / 998.23)
            W_tgv = 1.163 * Q_tgv * (List_arg[8] - List_arg[6])
            if params["exer_2"] == "2_7":
                dict_cost = {
                    "1": 16.784,
                    "2": 12.76,
                    "3": 19.20,
                    "4": 23.20,
                    "5": 17.74,
                    "6": 12.80
                }
                f = int(params["s_six_t"])
                key = params["s_six"]
                List_cost = []
                for i in dict_cost:
                    qu = res * W_tgv * f * dict_cost[i]
                    List_cost.append(qu)
                dict_val = {i: List_cost[i] for i in range(0, len(List_cost))}
                dfc = pd.DataFrame.from_dict(dict_val, orient='index')
                plt_obj = dfc.plot.bar(figsize=(30, 10))
            elif params["exer_2"] == "2_4":
                dict_gr = {}
                for i in range(-20, 20):
                    dict_gr.update({i: i * W_tgv})
                dfc = pd.DataFrame.from_dict(dict_gr, orient='index')
                plt_obj = dfc.plot(figsize=(30, 10), marker='.', markersize=35)
                plt_obj.grid()
        if plt_obj is not None:
            fig = plt_obj.get_figure()
            return fig
        return None
Пример #26
0
    '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
Пример #27
0
def main(filename, exit_at, size, offset, dpi, figsize, fps, bins_min, bins_max, bins_step, filename_out):
    # convert figsize (string like "8,9" to a list of float [8.0, 9.0]
    figsize = figsize.split(",")
    figsize = map(float, figsize)

    # Read CSV file to a Pandas DataFrame
    df = pd.read_csv(filename)
    df['Timestamp'] = pd.to_datetime(df['Timestamp'])
    df = df.set_index('Timestamp')
    #df = df.iloc[-10000:,:]
    df.index = df.index.tz_localize('UTC').tz_convert('UTC')

    # Get Numpy arrays from DataFrame
    direction = df['direction'].values
    var = df['speed'].values
    index = df.index.values

    # Define bins
    bins = np.arange(bins_min, bins_max, bins_step)

    # Create figure
    fig = plt.figure(figsize=figsize, dpi=dpi, facecolor='w', edgecolor='w')

    # Create a video writer (ffmpeg can create MPEG files)
    FFMpegWriter = mpl.animation.writers['ffmpeg']
    metadata = dict(title='windrose', artist='windrose',
            comment="""Made with windrose
http://www.github.com/scls19fr/windrose""")
    writer = FFMpegWriter(fps=fps, metadata=metadata)

    dt0 = index[offset]
    print("size: %d" % size)
    print("offset: %d" % offset)
    print("First dt: %s" % dt0)

    print("")

    dt2 = None
    i = 0
    with writer.saving(fig, filename_out, 100):
        #for i in range(1000): # 100
        try:
            while True: # loop until fails (end of data)
                print("Processing %d" % (i + 1))
                i1 = offset + i*size
                i2 = offset + (i+1)*size + 1

                index_tmp = index[i1:i2]
                dt1 = index_tmp[0]
                dt2 = index_tmp[-1]
                td = dt2 - dt1
                title = """  From %s
    to %s""" % (dt1, dt2)
                print(title)
                print("""    td %r""" % td.astype('timedelta64[m]'))
    
                try:
                    direction_tmp = direction[i1:i2]
                    var_tmp = var[i1:i2]

                    ax = WindroseAxes.from_ax(fig=fig) # scatter, bar, box, contour, contourf

                    #ax.scatter(direction_tmp, var_tmp, alpha=0.2)
                    #ax.set_xlim([-bins[-1], bins[-1]])
                    #ax.set_ylim([-bins[-1], bins[-1]])

                    #ax.bar(direction_tmp, var_tmp, bins=bins, normed=True, opening=0.8, edgecolor='white')

                    #ax.box(direction_tmp, var_tmp, bins=bins)

                    #ax.contour(direction_tmp, var_tmp, cmap=cm.hot, lw=3, bins=bins)

                    ax.contourf(direction_tmp, var_tmp, bins=bins, cmap=cm.hot)
                    ax.contour(direction_tmp, var_tmp, bins=bins, colors='black', lw=3)

                    ax.set_legend()

                    #ax = WindAxes.from_ax(fig=fig) # pdf: probability density function
                    #ax.pdf(var_tmp, bins=bins)
                    #ax.set_xlim([0, bins[-1]])
                    #ax.set_ylim([0, 0.4])

                    ax.set_title(title, fontname="Courier New")

                    writer.grab_frame()

                except:
                    print(traceback.format_exc(), file=sys.stderr)

                print("")

                fig.clf()
                i += 1
                if i == exit_at - 1: # exit_at must be > 1
                    break

        except:
            print(traceback.format_exc(), file=sys.stderr)

        print("First dt: %r" % dt0)
        print("Last  dt: %r" % dt2)
        td = dt2 - dt0
        print("      td: %r" % td.astype('timedelta64[D]'))
        N = i + 1
        print("Number of slides: %d" % N)


    #plt.show()

    print("")
    print("Save file to '%s'" % filename_out)
Пример #28
0
    def render(self):
        if len(self.line_list) != 1:
            log.error("Number of lines in polar plot should be 1")
            return

        line = self.line_list[0]
        if line.plot_type not in PolarPlot.plot_types:
            log.error(
                f"plot type {line.plot_type} not supported in polar plot")
            return
        if line.plot_type == 'windrose' and line.graph_type not in PolarPlot.graph_types:
            log.error(
                f"graph type {line.graph_type} not supported in polar plot")
            return

        # convert data to ndarrays and strip nans
        t = np.array(line.x)
        nant = np.isnan(t)
        if type(line.y[0]) == complex:
            y = np.array(line.y, dtype=np.complex64)
            nany = np.abs(y) <= 0.0
        else:
            y = np.array(line.y, dtype=np.float32)
            nany = np.isnan(y)
        nandata = np.logical_or(nant, nany)
        t = t[nandata == False]
        y = y[nandata == False]

        # for some reason, matplotlib works in inches and dpi
        size = (self.image_width / self.anti_alias) / 100.0, (
            self.image_height / self.anti_alias) / 100.0
        self.fig = plt.figure(figsize=size,
                              dpi=self.anti_alias * 100.0,
                              facecolor=int2rgbstr(
                                  self.chart_background_color))

        wd_radians = np.angle(y)
        wd = np.degrees(wd_radians)
        ws = np.abs(y)

        # make sure bars have rounded sides
        # see: https://github.com/python-windrose/windrose/issues/137
        rect = [0.1, 0.1, 0.8, 0.8]
        hist_ax = plt.Axes(self.fig, rect)
        hist_ax.bar(np.array([1]), np.array([1]))

        ax = WindroseAxes.from_ax(fig=self.fig)

        # make sure ticklabels and winding direction are ok
        # TODO make ticklables configurable
        ax.set_xticklabels(['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'])
        ax.set_theta_zero_location('N')
        ax.set_theta_direction(-1)

        if line.plot_type == 'windrose':
            if line.graph_type == 'bar':
                ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')
            elif line.graph_type == 'box':
                ax.box(wd, ws)
            elif line.graph_type == 'contour':
                ax.contourf(wd, ws)
            ax.set_legend()
        else:
            ax.scatter(-wd_radians, ws)
        return self.fig
Пример #29
0
def main(filename, exit_at, by, rmax, dpi, figsize, fps, bins_min, bins_max,
         bins_step, fontname, filename_out):
    # convert figsize (string like "8,9" to a list of float [8.0, 9.0]
    figsize = figsize.split(",")
    figsize = map(float, figsize)

    by_func = get_by_func(by)

    # Read CSV file to a Pandas DataFrame
    df_all = pd.read_csv(filename)
    df_all['Timestamp'] = pd.to_datetime(df_all['Timestamp'])
    df_all = df_all.set_index('Timestamp')

    df_all.index = df_all.index.tz_localize('UTC').tz_convert('UTC')

    dt_start = df_all.index[0]
    dt_end = df_all.index[-1]

    td = dt_end - dt_start
    Nslides = count(df_all, by_func)
    msg = """Starting
First dt: %s
Last  dt: %s
      td: %s
  Slides: %d""" % (dt_start, dt_end, td, Nslides)
    logger.info(msg)

    # Define bins
    bins = np.arange(bins_min, bins_max, bins_step)

    # Create figure
    fig = plt.figure(figsize=figsize, dpi=dpi, facecolor='w', edgecolor='w')

    # Create a video writer (ffmpeg can create MPEG files)
    FFMpegWriter = matplotlib.animation.writers['ffmpeg']
    metadata = dict(title='windrose',
                    artist='windrose',
                    comment="""Made with windrose
http://www.github.com/scls19fr/windrose""")
    writer = FFMpegWriter(fps=fps, metadata=metadata)

    dt_start_process = datetime.datetime.now()

    with writer.saving(fig, filename_out, 100):
        try:
            for i, df in enumerate(generate(df_all, by_func)):
                dt1 = df.index[0]
                dt2 = df.index[-1]
                td = dt2 - dt1
                msg = """  Slide %s/%s
    From %s
      to %s
      td %s""" % (i + 1, Nslides, dt1, dt2, td)
                logger.info(msg)
                remaining = Nslides - (i + 1)
                now = datetime.datetime.now()
                td_remaining = (now - dt_start_process) / (i + 1) * remaining
                logger.info("""    Expected
    time: %s
  end at: %s
""" % (td_remaining, now + td_remaining))

                title = "  From %s\n    to %s" % (dt1, dt2)

                try:
                    ax = WindroseAxes.from_ax(
                        fig=fig,
                        rmax=rmax)  # scatter, bar, box, contour, contourf

                    direction = df['direction'].values
                    var = df['speed'].values

                    # ax.scatter(direction, var, alpha=0.2)
                    # ax.set_xlim([-bins[-1], bins[-1]])
                    # ax.set_ylim([-bins[-1], bins[-1]])

                    # ax.bar(direction, var, bins=bins, normed=True, opening=0.8, edgecolor='white')

                    # ax.box(direction, var, bins=bins)

                    # ax.contour(direction, var, cmap=cm.hot, lw=3, bins=bins)

                    ax.contourf(direction, var, bins=bins, cmap=cm.hot)
                    ax.contour(direction, var, bins=bins, colors='black', lw=3)

                    ax.set_legend()

                    # ax = WindAxes.from_ax(fig=fig)  # pdf: probability density function
                    # ax.pdf(var, bins=bins)
                    # ax.set_xlim([0, bins[-1]])
                    # ax.set_ylim([0, 0.4])

                    ax.set_title(title, fontname=fontname)

                    writer.grab_frame()
                except KeyboardInterrupt:
                    break
                except Exception:
                    logger.error(traceback.format_exc())

                fig.clf()
                if i > exit_at - 1 and exit_at != 0:  # exit_at must be > 1
                    break
        except KeyboardInterrupt:
            return
        except Exception:
            logger.error(traceback.format_exc())

        N = i + 1
        logger.info("Number of slides: %d" % N)

    # plt.show()

    logger.info("Save file to '%s'" % filename_out)
Пример #30
0
 def new_axes():
     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)
     return ax, fig
Пример #31
0
# In[7]:


df_excel.shape


# In[15]:


from windrose import WindroseAxes
from matplotlib import pyplot as plt
import matplotlib.cm as cm

#gb = big_frame['Date'].groupby(pd.TimeGrouper(freq='M'))
ax = WindroseAxes.from_ax()
ax.box(df_excel['Dir 1'], df_excel['Wind Vel 1'], bins=np.arange(0,24,2))
ax.set_legend()
plt.show()


# In[16]:


ax = WindroseAxes.from_ax()
ax.box(df_excel['Dir 2'], df_excel['Wind Vel 2'], bins=np.arange(0,24,2))
ax.set_legend()
plt.show()


# In[17]:
Пример #32
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
    'Air pressure (hPa)'
]
gnl.plot_comp(df_all, df_interpol, varname1, varname2, varname3, 'U.Calg.',
              station + '_rh_pres')

varname1 = ['VW1', 'VW2', 'DW1', 'DW2']
varname2 = ['WindSpeedms', 'WindSpeedms', 'WindDirectiond', 'WindDirectiond']
varname3 = [
    'Wind speed 1 (m/s)', 'Wind speed 2 (m/s)', 'Wind direction 1 (d)',
    'Wind direction 2 (d)'
]
gnl.plot_comp(df_all, df_interpol, varname1, varname2, varname3, 'U.Calg.',
              station + '_wind')

fig = plt.figure(figsize=(10, 8))
ax = WindroseAxes.from_ax(fig=fig)
ws = np.abs(df_interpol['VW1'] - df_interpol['WindSpeedms'])
ws[ws < np.nanmean(ws)] = np.nan
wd = df_interpol['WindDirectiond']
ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')
ax.set_legend(title='Wind speed (m/s)')
ax.set_title(station)
fig.savefig('./Output/' + station + '_wind_bias_dir.png',
            bbox_inches='tight',
            dpi=200)

#% making day_night table

varname1 = ['TA1', 'TA2']
varname2 = ['AirTemperatureC', 'AirTemperatureC']
Пример #34
0
def main(filename, dpi, figsize, fps, bins_min, bins_max, bins_step,
         filename_out):
    # convert figsize (string like "8,9" to a list of float [8.0, 9.0]
    figsize = figsize.split(",")
    figsize = map(float, figsize)

    # Read CSV file to a Pandas DataFrame
    df_all = pd.read_csv(filename)
    df_all['Timestamp'] = pd.to_datetime(df_all['Timestamp'])
    df_all = df_all.set_index('Timestamp')
    df_all.index = df_all.index.tz_localize('UTC').tz_convert('UTC')
    # df_all = df_all.iloc[-10000:,:]
    df_all = df_all.ix['2011-07-01':'2011-12-31']

    # Get Numpy arrays from DataFrame
    direction_all = df_all['direction'].values
    var_all = df_all['speed'].values
    index_all = df_all.index.to_datetime()  # Fixed: .values -> to_datetime()
    by_all = df_all.index.map(by_func_monthly)
    by_unique = np.unique(by_all)
    print(by_unique)

    (ncols, nrows, nsheets) = (4, 3, 2)  # noqa

    # layout = Layout(4, 3, 2) # ncols, nrows, nsheets
    # layout = Layout(ncols, nrows, nsheets)

    # layout = Layout(4, 6, 1)
    # layout.save(ax)
    # layout.to_pdf("filename.pdf")
    # layout.to_video("filename.mp4")

    # fig, ax = plt.subplots(nrows=2, ncols=3)

    # with Layout(4, 6, 1) as layout:
    #     print(layout)
    #     #layout.save(ax)

    def tuple_position(i, ncols, nrows):
        i_sheet, sheet_pos = divmod(i, ncols * nrows)
        i_row, i_col = divmod(sheet_pos, ncols)
        return i_sheet, i_row, i_col

    def position_from_tuple(t, ncols, nrows):
        i_sheet, i_row, i_col = t
        return i_sheet * ncols * nrows + i_row * ncols + i_col

    assert tuple_position(0, ncols, nrows) == (0, 0, 0)
    assert tuple_position(1, ncols, nrows) == (0, 0, 1)
    assert tuple_position(2, ncols, nrows) == (0, 0, 2)
    assert tuple_position(3, ncols, nrows) == (0, 0, 3)
    assert tuple_position(4, ncols, nrows) == (0, 1, 0)
    assert tuple_position(5, ncols, nrows) == (0, 1, 1)
    assert tuple_position(6, ncols, nrows) == (0, 1, 2)
    assert tuple_position(7, ncols, nrows) == (0, 1, 3)
    assert tuple_position(8, ncols, nrows) == (0, 2, 0)
    assert tuple_position(9, ncols, nrows) == (0, 2, 1)
    assert tuple_position(10, ncols, nrows) == (0, 2, 2)
    assert tuple_position(11, ncols, nrows) == (0, 2, 3)
    assert tuple_position(12, ncols, nrows) == (1, 0, 0)
    assert tuple_position(13, ncols, nrows) == (1, 0, 1)
    assert tuple_position(14, ncols, nrows) == (1, 0, 2)
    assert tuple_position(15, ncols, nrows) == (1, 0, 3)
    assert tuple_position(16, ncols, nrows) == (1, 1, 0)
    assert tuple_position(17, ncols, nrows) == (1, 1, 1)

    assert position_from_tuple((0, 0, 0), ncols, nrows) == 0
    assert position_from_tuple((1, 0, 0), ncols, nrows) == ncols * nrows
    assert position_from_tuple((2, 0, 0), ncols, nrows) == 2 * ncols * nrows
    assert position_from_tuple((1, 0, 1), ncols, nrows) == ncols * nrows + 1
    assert position_from_tuple((1, 1, 1), ncols,
                               nrows) == ncols * nrows + ncols + 1
    assert position_from_tuple((1, 2, 3), ncols,
                               nrows) == ncols * nrows + 2 * ncols + 3

    for i in range(20):
        t = tuple_position(i, ncols, nrows)
        assert position_from_tuple(t, ncols, nrows) == i

    # layout = NormalLayout()

    # with layout.append() as ax:
    #     pass
    # layout.show()

    # Define bins
    bins = np.arange(bins_min, bins_max, bins_step)

    for by_value in by_unique:
        # by_value = (2011, 5)

        # mask = (by == by_value).all(axis=1)
        # ToFix: see http://stackoverflow.com/questions/32005403/boolean-indexing-with-numpy-array-and-tuples

        mask = (pd.Series(by_all) == by_value).values

        # print(mask)

        index = index_all[mask]
        var = var_all[mask]
        direction = direction_all[mask]

        # Create figure
        # fig = plt.figure(figsize=figsize, dpi=dpi, facecolor='w', edgecolor='w')

        # Same as above, but with contours over each filled region...
        ax = WindroseAxes.from_ax()
        ax.contourf(direction, var, bins=bins, cmap=cm.hot)
        ax.contour(direction, var, bins=bins, colors='black')
        fontname = "Courier"
        # title = by_value
        dt1 = index[0]
        dt2 = index[-1]
        # dt1 = df.index[mask][0]
        # dt2 = df.index[mask][-1]
        # td = dt2 - dt1
        title = "From %s\n  to %s" % (dt1, dt2)

        ax.set_title(title, fontname=fontname)
        ax.set_legend()

        plt.show()
Пример #35
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()
Пример #36
0
    def conditional_rate_of_occurrence(self,
                                       ds,
                                       t_window=pd.Timedelta(minutes=15),
                                       symmetric_t_window=False,
                                       dist_window=20,
                                       dim='speed',
                                       max_dim=200,
                                       windrose=True,
                                       **kwargs):
        '''
        Calculate the conditional rate of occurence

        Parameters
        ----------
        ds: dataset with coordinates lat, lon, and time
        t_window: pd.Timedelta of time window used to check for occurrences
        symmetric_t_window: bool indicating whether to look backwards in time
        dist_window: radius in km of window in which to check for occurrences
        dim: str dimension to pass to windrose
             -- 'speed', 'dist', 'hours', or 'minutes'
        max_dim: max dim to include in windrose can be set to None
        windrose: bool indicating whether or not to plot windrose
        **kwargs: passed on to windrose function

        Returns
        -------
        plot: windrose plot
        OR
        df: pandas.Dataframe containing bearing and dim info
        '''
        from geopy.distance import vincenty, great_circle

        zero_time = pd.Timedelta(seconds=0).asm8
        t_window = t_window.asm8

        if symmetric_t_window:
            t_window = t_window / 2

        lon = ds.lon.values
        lat = ds.lat.values
        time = ds.time.values
        loc = np.stack([lat, lon]).T

        dists = []
        bearings = []
        speeds = []
        t_diffs = []
        for t in time:
            if symmetric_t_window:
                t_diff = np.abs(time - t)
            else:
                t_diff = time - t
            bool_a = np.where((zero_time < t_diff) & (t_diff < t_window))

            little_loc = np.take(loc, bool_a, axis=0)[0]
            little_t_diff = np.take(t_diff, bool_a)[0]
            for ll, tt in zip(little_loc[1:], little_t_diff[1:]):
                if (ll == little_loc[0]).all():
                    continue
                dist = great_circle(little_loc[0], ll).km
                if dist < dist_window:
                    hours = (int(tt) / 10e8 / 60 / 60.)
                    t_diffs.append(hours)
                    dists.append(dist)
                    speeds.append(dist / hours)
                    bearings.append(calculate_bearing(little_loc[0], ll))
        df = pd.DataFrame({
            'speed': speeds,
            'dist': dists,
            'hours': t_diffs,
            'direction': bearings
        })
        if dim == 'minutes':
            df = df.assign(minutes=df.hours * 60)
        if not windrose:
            return df
        else:
            from windrose import WindroseAxes

            if max_dim is not None:
                df = df[df[dim].abs() < max_dim]
            max_dim = max_dim or df[dim].abs().max()

            ax = WindroseAxes.from_ax()
            ax.bar(df['direction'],
                   df[dim],
                   bins=kwargs.pop('bins', np.arange(0, max_dim, 20)),
                   normed=kwargs.pop('normed', True),
                   opening=kwargs.pop('opening', 0.9),
                   edgecolor=kwargs.pop('edgecolor', 'white'),
                   **kwargs)
            ax.set_legend()

            return ax
Пример #37
0
        p1.set_ylabel('Count', size=12)
        for lb in p1.xaxis.get_ticklabels():
            lb.set_fontsize(11)
        for lb in p1.yaxis.get_ticklabels():
            lb.set_fontsize(11)
        tstr = '%s Wind Speed' % (stns[j])
        pyplot.title(tstr, size=14)
        pngnm = '%s_WindSpeedHist.png' % (stns[j])
        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()
Пример #38
0
def main(filename, dpi, figsize, fps, bins_min, bins_max, bins_step, filename_out):
    # convert figsize (string like "8,9" to a list of float [8.0, 9.0]
    figsize = figsize.split(",")
    figsize = map(float, figsize)

    # Read CSV file to a Pandas DataFrame
    df_all = pd.read_csv(filename)
    df_all['Timestamp'] = pd.to_datetime(df_all['Timestamp'])
    df_all = df_all.set_index('Timestamp')
    df_all.index = df_all.index.tz_localize('UTC').tz_convert('UTC')
    #df_all = df_all.iloc[-10000:,:]    
    df_all = df_all['2011-07-01':'2011-12-31']

    # Get Numpy arrays from DataFrame
    direction_all = df_all['direction'].values
    var_all = df_all['speed'].values
    index_all = df_all.index.to_datetime() #Fixed: .values -> to_datetime()
    by_all = df_all.index.map(by_func_monthly)
    by_unique = np.unique(by_all)
    print(by_unique)

    (ncols, nrows, nsheets) = (4, 3, 2)
    #layout = Layout(4, 3, 2) # ncols, nrows, nsheets
    layout = Layout(ncols, nrows, nsheets)
    def tuple_position(i, ncols, nrows):
        i_sheet, sheet_pos = divmod(i, ncols*nrows)
        i_row, i_col  = divmod(sheet_pos, ncols)
        return i_sheet, i_row, i_col

    def position_from_tuple(t, ncols, nrows):
        i_sheet, i_row, i_col = t
        return i_sheet * ncols * nrows + i_row * ncols + i_col

    assert  tuple_position(0, ncols, nrows) == (0, 0, 0)
    assert  tuple_position(1, ncols, nrows) == (0, 0, 1)
    assert  tuple_position(2, ncols, nrows) == (0, 0, 2)
    assert  tuple_position(3, ncols, nrows) == (0, 0, 3)
    assert  tuple_position(4, ncols, nrows) == (0, 1, 0)
    assert  tuple_position(5, ncols, nrows) == (0, 1, 1)
    assert  tuple_position(6, ncols, nrows) == (0, 1, 2)
    assert  tuple_position(7, ncols, nrows) == (0, 1, 3)
    assert  tuple_position(8, ncols, nrows) == (0, 2, 0)
    assert  tuple_position(9, ncols, nrows) == (0, 2, 1)
    assert tuple_position(10, ncols, nrows) == (0, 2, 2)
    assert tuple_position(11, ncols, nrows) == (0, 2, 3)
    assert tuple_position(12, ncols, nrows) == (1, 0, 0)
    assert tuple_position(13, ncols, nrows) == (1, 0, 1)
    assert tuple_position(14, ncols, nrows) == (1, 0, 2)
    assert tuple_position(15, ncols, nrows) == (1, 0, 3)
    assert tuple_position(16, ncols, nrows) == (1, 1, 0)
    assert tuple_position(17, ncols, nrows) == (1, 1, 1)

    assert position_from_tuple((0, 0, 0), ncols, nrows) == 0
    assert position_from_tuple((1, 0, 0), ncols, nrows) == ncols * nrows
    assert position_from_tuple((2, 0, 0), ncols, nrows) == 2 * ncols * nrows
    assert position_from_tuple((1, 0, 1), ncols, nrows) == ncols * nrows + 1
    assert position_from_tuple((1, 1, 1), ncols, nrows) == ncols * nrows + ncols + 1
    assert position_from_tuple((1, 2, 3), ncols, nrows) == ncols * nrows + 2 * ncols + 3

    for i in range(20):
        t = tuple_position(i, ncols, nrows)
        assert position_from_tuple(t, ncols, nrows) == i

    #layout = NormalLayout()

    #with layout.append() as ax:
    #    pass
    #layout.show()

    # Define bins
    bins = np.arange(bins_min, bins_max, bins_step)

    for by_value in by_unique:
        #by_value = (2011, 5)

        #mask = (by == by_value).all(axis=1)
        # ToFix: see http://stackoverflow.com/questions/32005403/boolean-indexing-with-numpy-array-and-tuples

        mask = (pd.Series(by_all) == by_value).values

        #print(mask)

        index = index_all[mask]
        var = var_all[mask]
        direction = direction_all[mask]

        # Create figure
        #fig = plt.figure(figsize=figsize, dpi=dpi, facecolor='w', edgecolor='w')

        #Same as above, but with contours over each filled region...
        ax = WindroseAxes.from_ax()
        ax.contourf(direction, var, bins=bins, cmap=cm.hot)
        ax.contour(direction, var, bins=bins, colors='black')
        fontname = "Courier"
        #title = by_value
        dt1 = index[0]
        dt2 = index[-1]
        #dt1 = df.index[mask][0]
        #dt2 = df.index[mask][-1]
        td = dt2 - dt1
        title = "From %s\n  to %s" % (dt1, dt2)

        ax.set_title(title, fontname=fontname)
        ax.set_legend()

        plt.show()
Пример #39
0
def main(filename, exit_at, by, rmax, dpi, figsize, fps, bins_min, bins_max, bins_step, fontname, filename_out):
    # convert figsize (string like "8,9" to a list of float [8.0, 9.0]
    figsize = figsize.split(",")
    figsize = map(float, figsize)

    by_func = get_by_func(by)

    # Read CSV file to a Pandas DataFrame
    df_all = pd.read_csv(filename)
    df_all['Timestamp'] = pd.to_datetime(df_all['Timestamp'])
    df_all = df_all.set_index('Timestamp')

    df_all.index = df_all.index.tz_localize('UTC').tz_convert('UTC')

    dt_start = df_all.index[0]
    dt_end = df_all.index[-1]

    td = dt_end - dt_start
    Nslides = count(df_all, by_func)
    msg = """Starting
First dt: %s
Last  dt: %s
      td: %s
  Slides: %d""" % (dt_start, dt_end, td, Nslides)
    logger.info(msg)

    # Define bins
    bins = np.arange(bins_min, bins_max, bins_step)

    # Create figure
    fig = plt.figure(figsize=figsize, dpi=dpi, facecolor='w', edgecolor='w')

    # Create a video writer (ffmpeg can create MPEG files)
    FFMpegWriter = matplotlib.animation.writers['ffmpeg']
    metadata = dict(title='windrose', artist='windrose',
                    comment="""Made with windrose
http://www.github.com/scls19fr/windrose""")
    writer = FFMpegWriter(fps=fps, metadata=metadata)

    dt_start_process = datetime.datetime.now()

    with writer.saving(fig, filename_out, 100):
        try:
            for i, df in enumerate(generate(df_all, by_func)):
                dt1 = df.index[0]
                dt2 = df.index[-1]
                td = dt2 - dt1
                msg = """  Slide %s/%s
    From %s
      to %s
      td %s""" % (i + 1, Nslides, dt1, dt2, td)
                logger.info(msg)
                remaining = Nslides - (i + 1)
                now = datetime.datetime.now()
                td_remaining = (now - dt_start_process) / (i + 1) * remaining
                logger.info("""    Expected
    time: %s
  end at: %s
""" % (td_remaining, now + td_remaining))

                title = "  From %s\n    to %s" % (dt1, dt2)

                try:
                    ax = WindroseAxes.from_ax(fig=fig, rmax=rmax)  # scatter, bar, box, contour, contourf

                    direction = df['direction'].values
                    var = df['speed'].values

                    # ax.scatter(direction, var, alpha=0.2)
                    # ax.set_xlim([-bins[-1], bins[-1]])
                    # ax.set_ylim([-bins[-1], bins[-1]])

                    # ax.bar(direction, var, bins=bins, normed=True, opening=0.8, edgecolor='white')

                    # ax.box(direction, var, bins=bins)

                    # ax.contour(direction, var, cmap=cm.hot, lw=3, bins=bins)

                    ax.contourf(direction, var, bins=bins, cmap=cm.hot)
                    ax.contour(direction, var, bins=bins, colors='black', lw=3)

                    ax.set_legend()

                    # ax = WindAxes.from_ax(fig=fig)  # pdf: probability density function
                    # ax.pdf(var, bins=bins)
                    # ax.set_xlim([0, bins[-1]])
                    # ax.set_ylim([0, 0.4])

                    ax.set_title(title, fontname=fontname)

                    writer.grab_frame()
                except KeyboardInterrupt:
                    break
                except Exception:
                    logger.error(traceback.format_exc())

                fig.clf()
                if i > exit_at - 1 and exit_at != 0:  # exit_at must be > 1
                    break
        except KeyboardInterrupt:
            return
        except Exception:
            logger.error(traceback.format_exc())

        N = i + 1
        logger.info("Number of slides: %d" % N)

    # plt.show()

    logger.info("Save file to '%s'" % filename_out)
Пример #40
0
def new_axes():
    fig = plt.figure(figsize=(4, 4), dpi=80, facecolor='w', edgecolor='w')
    rect = [0, 0, 1, 1]
    ax = WindroseAxes(fig, rect, axisbg='w')
    fig.add_axes(ax)
    return ax
Пример #41
0
def 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)
    winddir = metdat[dircol]
    var = metdat[varcol]

    # 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])

    # built figure
    fig = plt.figure()
    ax = WindroseAxes.from_ax(fig=fig)
    ax.bar(winddir,
           var,
           normed=True,
           opening=0.95,
           edgecolor='white',
           bins=bins,
           nsector=nsector,
           colors=colors,
           linewidth=0.35)

    # legend
    leg = ['blank']
    if noleg is not True:
        leg = ax.set_legend(loc=7,
                            bbox_to_anchor=(1.55, 0.5),
                            fontsize=10,
                            frameon=False)
        # add labels to legend
        leg.set_title(catinfo['labels'][category])
        fig.text(0.875, 0.275, r'$z={}$ m'.format(vertloc))

    # adjust plot for specified max frequency
    if ylim is None:
        ylim = ax.get_ylim()[-1]

    # frequency axis limits and labels
    ax.set_ylim(0, ylim)
    ax.set_yticks(np.linspace(0, ylim, 4))
    ax.set_yticklabels([str(round(x, 1)) for x in np.linspace(0, ylim, 4)])

    return fig, ax, leg
Пример #42
0
        p1.set_xticks(bspt)
        p1.set_xticklabels(vscts[bspt])
        for lb in p1.xaxis.get_ticklabels():
            lb.set_fontsize(11)
        for lb in p1.yaxis.get_ticklabels():
            lb.set_fontsize(11)
        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(
Пример #43
0
    def conditional_rate_of_occurrence(self, ds,
                                       t_window=pd.Timedelta(minutes=15),
                                       symmetric_t_window=False,
                                       dist_window=20, dim='speed',
                                       max_dim=200,
                                       windrose=True, **kwargs):
        '''
        Calculate the conditional rate of occurence

        Parameters
        ----------
        ds: dataset with coordinates lat, lon, and time
        t_window: pd.Timedelta of time window used to check for occurrences
        symmetric_t_window: bool indicating whether to look backwards in time
        dist_window: radius in km of window in which to check for occurrences
        dim: str dimension to pass to windrose
             -- 'speed', 'dist', 'hours', or 'minutes'
        max_dim: max dim to include in windrose can be set to None
        windrose: bool indicating whether or not to plot windrose
        **kwargs: passed on to windrose function

        Returns
        -------
        plot: windrose plot
        OR
        df: pandas.Dataframe containing bearing and dim info
        '''
        from geopy.distance import vincenty, great_circle

        zero_time = pd.Timedelta(seconds=0).asm8
        t_window = t_window.asm8

        if symmetric_t_window:
            t_window = t_window/2

        lon = ds.lon.values
        lat = ds.lat.values
        time = ds.time.values
        loc = np.stack([lat, lon]).T

        dists = []
        bearings = []
        speeds = []
        t_diffs = []
        for t in time:
            if symmetric_t_window:
                t_diff = np.abs(time-t)
            else:
                t_diff = time-t
            bool_a = np.where((zero_time < t_diff) & (t_diff < t_window))

            little_loc = np.take(loc, bool_a, axis=0)[0]
            little_t_diff = np.take(t_diff, bool_a)[0]
            for ll, tt in zip(little_loc[1:], little_t_diff[1:]):
                if (ll == little_loc[0]).all():
                    continue
                dist = great_circle(little_loc[0], ll).km
                if dist < dist_window:
                    hours = (int(tt)/10e8/60/60.)
                    t_diffs.append(hours)
                    dists.append(dist)
                    speeds.append(dist/hours)
                    bearings.append(calculate_bearing(little_loc[0], ll))
        df = pd.DataFrame({'speed': speeds, 'dist': dists, 'hours': t_diffs,
                           'direction': bearings})
        if dim == 'minutes':
            df = df.assign(minutes=df.hours*60)
        if not windrose:
            return df
        else:
            from windrose import WindroseAxes

            if max_dim is not None:
                df = df[df[dim].abs() < max_dim]
            max_dim = max_dim or df[dim].abs().max()

            ax = WindroseAxes.from_ax()
            ax.bar(df['direction'], df[dim],
                   bins=kwargs.pop('bins', np.arange(0, max_dim, 20)),
                   normed=kwargs.pop('normed', True),
                   opening=kwargs.pop('opening', 0.9),
                   edgecolor=kwargs.pop('edgecolor', 'white'),
                   **kwargs)
            ax.set_legend()

            return ax
Пример #44
0
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
Пример #45
0
from windrose import WindroseAxes

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

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.