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

ax.set_rlabel_position(340)  #122, 344, 198, 340
ax.set_rmax(10)  #8, 10
ax.set_rticks(np.arange(0, 11, 2))
ax.set_yticklabels(['', '  2%', '  4%', '  6%', '  8%', '  10%'],
                   fontsize=tk_fs)
#ax.set_yticklabels(['','2%','4%','6%','8%','10%'], fontsize=tk_fs)

rect = [0.52, 0, 0.5, 1]
ax = WindroseAxes(fig, rect)
fig.add_axes(ax)

ax.bar(WD_b,
       WS_b,
       cmap=cm.viridis,
       normed=True,
       nsector=36,
示例#2
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