Exemplo n.º 1
0
def test_non_tuple_rgbaface():
    # This passes rgbaFace as a ndarray to draw_path.
    fig = plt.figure()
    fig.add_subplot(projection="3d").scatter(
        [0, 1, 2], [0, 1, 2], path_effects=[patheffects.Stroke(linewidth=4)])
    fig.canvas.draw()
Exemplo n.º 2
0
                           np.arange(1, 52, 1),
                           tf_pcacf[:, 1:].T,
                           vmin=0,
                           vmax=0.04,
                           cmap=cmap,
                           rasterized=True)
if np.any(tf_pcacf_p < 0.05):
    co = pc_cacf_ax.contour(trial_t,
                            np.arange(1, 51, 1),
                            tf_pcacf_p[:, 1:].T,
                            levels=[0.05],
                            colors='w',
                            linewidths=0.75)
    plt.setp(co.collections,
             path_effects=([
                 path_effects.Stroke(linewidth=2., foreground='black'),
                 path_effects.Normal()
             ]))

pc_cacf_ax.axvline(0, ls='-', c='k', lw=0.5)
pc_cacf_ax.set_xlabel('time relative to stimulus (ms)')
pc_cacf_ax.set_ylabel('lag (trials)')
pc_cacf_ax.set_title(r'smoothed partial acf of phases')

cb_ax = fig.add_subplot(gs2[1, 0])
plt.colorbar(pc,
             cax=cb_ax,
             label='partial circular correlation coefficient',
             orientation='horizontal',
             ticks=[0, 0.01, 0.02, 0.03, 0.04])
Exemplo n.º 3
0
    patch = pl.fill(radec[:, 0],
                    radec[:, 1],
                    lw=0,
                    facecolor="#27ae60",
                    zorder=100)
    superstamp_patches.append(patch)
text = pl.text(268.6,
               -27.6,
               'Microlensing\nsuperstamp',
               color='#27ae60',
               zorder=999,
               fontsize=22,
               va='center',
               ha='left')
text.set_path_effects([
    path_effects.Stroke(linewidth=4, foreground='white'),
    path_effects.Normal()
])
"""
annotate_target(187.27789633, 2.05240632, "3C 273")
annotate_target(180.44154, -3.76128, "GW Vir", ha='right')
"""

# Mars was in the field when C9 started on April 21st
ra = [
    264.32006, 266.32142, 268.32035, 270.31586, 272.30694, 274.29257,
    276.27171, 278.24329, 280.20625, 282.15951
]
dec = [
    -23.25199, -23.38232, -23.48986, -23.57480, -23.63741, -23.67799,
    -23.69692, -23.69462, -23.67157, -23.62832
Exemplo n.º 4
0
def plot_fixed_points(adata,
                      vecfld,
                      basis='X_umap',
                      marker="o",
                      markersize=200,
                      c='w',
                      cmap=None,
                      filltype=["full", "top", "none"],
                      background=None,
                      save_show_or_return="return",
                      save_kwargs={},
                      ax=None,
                      **kwargs):
    """Plot fixed points stored in the VectorField2D class.

    Arguments
    ---------
        vecfld: :class:`~vector_field`
            An instance of the vector_field class.
        basis: `str` (default: 'umap')
            The basis on which the fixed points are ploted.
        marker: `str` (default: `o`)
            The marker type. Any string supported by matplotlib.markers.
        markersize: `float` (default: 200)
            The size of the marker.
        cmap: string (optional, default 'Blues')
            The name of a matplotlib colormap to use for coloring or shading the confidence of fixed points. If None, the
            default color map will set to be viridis (inferno) when the background is white (black).
        filltype: list
            The fill type used for stable, saddle, and unstable fixed points. Default is 'full', 'top' and 'none',
            respectively.
        background: `str` or None (default: None)
            The background color of the plot.
        save_show_or_return: {'show', 'save', 'return'} (default: `return`)
            Whether to save, show or return the figure.
        save_kwargs: `dict` (default: `{}`)
            A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig function
            will use the {"path": None, "prefix": 'plot_fixed_points', "dpi": None, "ext": 'pdf', "transparent": True, "close":
            True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those keys
            according to your needs.
        ax: :class:`~matplotlib.axes.Axes`
            The matplotlib axes used for plotting. Default is to use the current axis.
        kwargs:
            Key word arguments passed to the find_fixed_point function of the vector field class for high dimension fixed
            point identification.
    """

    import matplotlib
    from matplotlib import rcParams, markers
    import matplotlib.patheffects as PathEffects
    from matplotlib.colors import to_hex

    if background is None:
        _background = rcParams.get("figure.facecolor")
        _background = to_hex(
            _background) if type(_background) is tuple else _background
    else:
        _background = background

    if _background in ["#ffffff", "black"]:
        _theme_ = "inferno"
    else:
        _theme_ = "viridis"
    _cmap = _themes[_theme_]["cmap"] if cmap is None else cmap

    Xss, ftype = vecfld.get_fixed_points(**kwargs)
    if Xss.shape[1] > 2:
        fp_ind = nearest_neighbors(Xss, vecfld.data['X'], 1).flatten()
        # fix the bug when certain cells are filtered during the vector field learning
        Xss = adata.obsm[basis][fp_ind]

    if ax is None:
        ax = plt.gca()

    for i in range(len(Xss)):
        cur_ftype = ftype[i]
        marker_ = markers.MarkerStyle(marker=marker,
                                      fillstyle=filltype[int(cur_ftype + 1)])
        ax.scatter(
            *Xss[i],
            marker=marker_,
            s=markersize,
            c=c,
            edgecolor=_select_font_color(_background),
            linewidths=1,
            cmap=_cmap,
            vmin=0,
            zorder=5,
        )
        txt = ax.text(
            *Xss[i],
            repr(i),
            c=("black"
               if cur_ftype == -1 else "blue" if cur_ftype == 0 else "red"),
            horizontalalignment="center",
            verticalalignment="center",
            zorder=6,
            weight="bold",
        )
        txt.set_path_effects([
            PathEffects.Stroke(linewidth=1.5,
                               foreground=_background,
                               alpha=0.8),
            PathEffects.Normal(),
        ])

    if save_show_or_return == "save":
        s_kwargs = {
            "path": None,
            "prefix": "plot_fixed_points",
            "dpi": None,
            "ext": "pdf",
            "transparent": True,
            "close": True,
            "verbose": True,
        }
        s_kwargs = update_dict(s_kwargs, save_kwargs)

        save_fig(**s_kwargs)
    elif save_show_or_return == "show":
        plt.tight_layout()
        plt.show()
    elif save_show_or_return == "return":
        return ax
Exemplo n.º 5
0
def _draw_outline(o, lw: int):
    "Outline bounding box onto image `Patch`."
    o.set_path_effects([
        patheffects.Stroke(linewidth=lw, foreground='black'),
        patheffects.Normal()
    ])
Exemplo n.º 6
0
def draw_T_2m(T_2m=None,
              map_extent=(50, 150, 0, 65),
              regrid_shape=20,
              add_china=True,
              city=True,
              south_China_sea=True,
              output_dir=None,
              Global=False):
    # set font
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    # set figure
    plt.figure(figsize=(16, 9))

    if (Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(
            central_latitude=(map_extent[2] + map_extent[3]) / 2.,
            central_longitude=(map_extent[0] + map_extent[1]) / 2.,
            standard_parallels=[30., 60.])

    ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs)
    datacrs = ccrs.PlateCarree()
    map_extent2 = utl.adjust_map_ratio(ax,
                                       map_extent=map_extent,
                                       datacrs=datacrs)

    # define return plots
    plots = {}
    if T_2m is not None:
        x, y = np.meshgrid(T_2m['lon'], T_2m['lat'])
        z = np.squeeze(T_2m['data'])
        cmap = dk_ctables.cm_temp()
        cmap.set_under(color=[0, 0, 0, 0], alpha=0.0)
        plots['T_2m'] = ax.pcolormesh(x,
                                      y,
                                      z,
                                      cmap=cmap,
                                      zorder=1,
                                      transform=datacrs,
                                      alpha=0.5,
                                      vmin=-45,
                                      vmax=45)

        z = gaussian_filter(z, 5)
        plots['T_2m_zero'] = ax.contour(x,
                                        y,
                                        z,
                                        levels=[0],
                                        colors='#232B99',
                                        linewidths=2,
                                        transform=datacrs,
                                        zorder=2)
        cl_zero = plt.clabel(plots['T_2m_zero'],
                             inline=1,
                             fontsize=15,
                             fmt='%i',
                             colors='#232B99')
        for t in cl_zero:
            t.set_path_effects([
                mpatheffects.Stroke(linewidth=3, foreground='white'),
                mpatheffects.Normal()
            ])

        plots['T_2m_35'] = ax.contour(x,
                                      y,
                                      z,
                                      levels=[35, 37, 40],
                                      colors=['#FF8F00', '#FF6200', '#FF0000'],
                                      linewidths=2,
                                      transform=datacrs,
                                      zorder=2)
        cl_35 = plt.clabel(plots['T_2m_35'],
                           inline=1,
                           fontsize=15,
                           fmt='%i',
                           colors='#FF0000')
        for t in cl_35:
            t.set_path_effects([
                mpatheffects.Stroke(linewidth=3, foreground='white'),
                mpatheffects.Normal()
            ])

    plt.title('[' + T_2m.attrs['model'] + ']' + ' ' + T_2m.attrs['title'],
              loc='left',
              fontsize=30)

    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(ax,
                                      name='coastline',
                                      edgecolor='gray',
                                      lw=0.8,
                                      zorder=4,
                                      alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(ax,
                                          name='province',
                                          edgecolor='gray',
                                          lw=0.5,
                                          zorder=4)
        utl.add_china_map_2cartopy_public(ax,
                                          name='nation',
                                          edgecolor='black',
                                          lw=0.8,
                                          zorder=4)
        utl.add_china_map_2cartopy_public(ax,
                                          name='river',
                                          edgecolor='#74b9ff',
                                          lw=0.8,
                                          zorder=4,
                                          alpha=0.5)

    # grid lines
    gl = ax.gridlines(crs=datacrs,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--',
                      zorder=5)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    utl.add_cartopy_background(ax, name='RD')

    l, b, w, h = ax.get_position().bounds

    #forecast information
    bax = plt.axes([l, b + h - 0.1, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(
        str(T_2m.coords['forecast_reference_time'].values)).replace(
            tzinfo=None).to_pydatetime()
    fcst_time = initTime + timedelta(
        hours=T_2m.coords['forecast_period'].values[0])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5, 5, '预报时间: ' + fcst_time.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5,
             2.5,
             '预报时效: ' + str(int(T_2m.coords['forecast_period'].values[0])) +
             '小时',
             size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    if (T_2m != None):
        cax = plt.axes([l, b - 0.04, w, .02])
        cb = plt.colorbar(plots['T_2m'], cax=cax, orientation='horizontal')
        cb.ax.tick_params(labelsize='x-large')
        cb.set_label(u'°C', size=20)

    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l + w - 0.091, b, .1, .2])

    small_city = False
    #if(map_extent2[1]-map_extent2[0] < 25):
    #    small_city=True
    #if city:
    utl.add_city_and_number_on_map(ax,
                                   data=T_2m,
                                   map_extent=map_extent2,
                                   transform=datacrs,
                                   zorder=6,
                                   size=13,
                                   small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[l - 0.02, b + h - 0.1, .1, .1],
                               which='nmc',
                               size='Xlarge')

    # show figure
    if (output_dir != None):
        plt.savefig(output_dir + '最低温度_预报_' + '起报时间_' +
                    initTime.strftime("%Y年%m月%d日%H时") + '预报时效_' +
                    str(T_2m.coords['forecast_period'].values[0]) + '小时' +
                    '.png',
                    dpi=200)
    if (output_dir == None):
        plt.show()
Exemplo n.º 7
0
def my_own_quiver_function(axis,
                           X_pos,
                           Y_pos,
                           X_val,
                           Y_val,
                           plot_velocity_legend='False',
                           standard_vel=5,
                           limits=None,
                           Z_val=None):
    global fontsize_global
    if plot_velocity_legend == 'False' or plot_velocity_legend == False:
        plot_velocity_legend = False
        legend_text = ''
    elif plot_velocity_legend == 'True' or plot_velocity_legend == True:
        plot_velocity_legend = True
        if standard_vel > 1.0:
            legend_text = str(int(standard_vel)) + "kms$^{-1}$"
        else:
            legend_text = str(int(standard_vel * 10.) / 10.) + "kms$^{-1}$"
    standard_vel = yt.units.km.in_units('cm').value * standard_vel
    if limits is None:
        xmin = np.min(X_pos)
        xmax = np.max(X_pos)
        ymin = np.min(Y_pos)
        ymax = np.max(Y_pos)
    else:
        xmin = limits[0][0]
        xmax = limits[0][1]
        ymin = limits[1][0]
        ymax = limits[1][1]
    rv_colors = np.linspace(-1, 1, 256)
    rv_cmap = plt.cm.get_cmap('bwr')

    len_scale = standard_vel / (0.07 * (xmax - xmin))
    vels = np.hypot(X_val, Y_val)
    for xp in range(len(X_pos[0])):
        for yp in range(len(Y_pos[0])):
            xvel = X_val[xp][yp] / len_scale
            yvel = Y_val[xp][yp] / len_scale
            width_val = np.sqrt(X_val[xp][yp]**2. +
                                Y_val[xp][yp]**2.) / standard_vel
            if width_val > 0.8:
                width_val = 0.8
            try:
                if Z_val == None:
                    color = 'w'
            except:
                #cmap = 'idl06_r'
                zvel = Z_val[xp][yp] / len_scale
                cit = np.argmin(abs(rv_colors - zvel))
                color = rv_cmap(cit)
            axis.add_patch(
                mpatches.FancyArrowPatch(
                    (X_pos[xp][yp], Y_pos[xp][yp]),
                    (X_pos[xp][yp] + xvel, Y_pos[xp][yp] + yvel),
                    color=color,
                    linewidth=1. * width_val,
                    arrowstyle='->',
                    mutation_scale=15. * width_val,
                    shrinkA=0.0,
                    shrinkB=0.0))
    if plot_velocity_legend:
        #print("plotting quiver legend")
        pos_start = [xmax - 0.15 * (xmax - xmin), ymin + 0.07 * (ymax - ymin)]
        xvel = standard_vel / len_scale
        yvel = 0.0
        width_val = 1.0
        axis.add_patch(
            mpatches.FancyArrowPatch(
                (pos_start[0], pos_start[1]),
                (pos_start[0] + xvel, pos_start[1] + yvel),
                arrowstyle='->',
                color='w',
                linewidth=1. * width_val,
                mutation_scale=15. * width_val))
        annotate_text = axis.text((xmax - 0.01 * (xmax - xmin)),
                                  (ymin + 0.03 * (ymax - ymin)),
                                  legend_text,
                                  va="center",
                                  ha="right",
                                  color='w',
                                  fontsize=fontsize_global)
        annotate_text.set_path_effects([
            path_effects.Stroke(linewidth=3, foreground='black'),
            path_effects.Normal()
        ])
    return axis
Exemplo n.º 8
0
def model_electrophysiological_fit(layer_fit, ax):

    ################# AESTHETICS
    v4_color = 'black'
    it_color = 'black'
    n_layers = len(layer_fit['layers'])
    v4 = layer_fit['v4']
    it = layer_fit['it']
    delta = layer_fit['delta']
    alpha = .1

    ################## V4
    plt.plot(v4['mu'],
             color=v4_color,
             linestyle='--',
             linewidth=1,
             alpha=1,
             label='V4')
    v4_min = v4['mu'] - (v4['std'] / np.sqrt(n_layers))
    v4_max = v4['mu'] + (v4['std'] / np.sqrt(n_layers))
    plt.fill_between(x=range(n_layers),
                     y1=v4_min,
                     y2=v4_max,
                     color=v4_color,
                     alpha=alpha,
                     edgecolor='')
    annotate_fit_to_layer('v4', layer_fit)

    ################## IT
    plt.plot(it['mu'],
             color=it_color,
             linestyle='-',
             linewidth=1,
             alpha=1,
             label='IT')
    it_min = it['mu'] - (it['std'] / np.sqrt(n_layers))
    it_max = it['mu'] + (it['std'] / np.sqrt(n_layers))
    plt.fill_between(x=range(n_layers),
                     y1=it_min,
                     y2=it_max,
                     color=it_color,
                     alpha=alpha,
                     edgecolor='')
    annotate_fit_to_layer('it', layer_fit)

    ################ DELTA
    import matplotlib.patheffects as pe
    params = {
        'solid_capstyle': 'round',
        'linewidth': 5,
        'zorder': 1,
    }
    plt.plot(
        range(n_layers),
        delta,
        color='white',
        label='$\Delta_{IT - V4}$',
        path_effects=[pe.Stroke(linewidth=3, foreground='black'),
                      pe.Normal()],
    )
    plt.ylim(min(delta) - .1, max(v4['mu']) + .15)

    ################ LABELS
    plt.yticks(size=6)
    plt.ylabel('Cross-validated fit to Neural Data', labelpad=0, fontsize=11)
    plt.xlabel("Model Layer", labelpad=5, fontsize=10)
    plt.xticks(range(n_layers), layer_fit['layers'], rotation=90, fontsize=7)
    plt.legend(framealpha=0, fontsize=9, title_fontsize=9, loc=4)
            arrowprops=dict(arrowstyle="simple",
                            fc="#aaaaaa", ec="none",
                            connectionstyle="arc3,rad=0.0"),
            )

annotate_target(127.578771, +22.235908, "K2-34")
annotate_target(126.61603759, +10.08037466, "HIP 41378")

# Plot the Beehive cluster
import pandas as pd
df = pd.read_csv('catalogs/beehive.csv')
for member in df.iterrows():
    annotate_target(member[1].RA_d, member[1].DEC_d, "", size=10, color='#c0392b')
text = pl.text(130., 20.5, 'M44 (Beehive)', style='italic', color='black',
               zorder=999, fontsize=30, va='center', ha='center')
text.set_path_effects([path_effects.Stroke(linewidth=4, foreground='white'),
                       path_effects.Normal()])

# Plot the M67 cluster
df = pd.read_csv('catalogs/m67.csv')
for member in df.iterrows():
    annotate_target(member[1].RA_d, member[1].DEC_d, "", size=10, color='#c0392b')
text = pl.text(132.8250 - 0.6, +11.8000, 'M67', style='italic', color='black',
               zorder=999, fontsize=30, va='center')
text.set_path_effects([path_effects.Stroke(linewidth=4, foreground='white'),
                       path_effects.Normal()])


# Plot the M67 cluster
#df = pd.read_csv('catalogs/stello-m67-paper.txt')
#for member in df.iterrows():
Exemplo n.º 10
0
def plot_map_standard(proj,
                      point_locs,
                      df_t,
                      area='EU',
                      west=-9.5,
                      east=28,
                      south=35,
                      north=62,
                      fonts=14,
                      path=None,
                      SLP=False,
                      gust=False):
    if path == None:
        # set up the paths and test for existence
        path = expanduser('~') + '/Documents/Metar_plots'
        try:
            os.listdir(path)
        except FileNotFoundError:
            os.mkdir(path)
    else:
        path = path
    df = df_t.loc[(df_t['longitude'] >= west - 4)
                  & (df_t['longitude'] <= east + 4)
                  & (df_t['latitude'] <= north + 4) &
                  (df_t['latitude'] >= south - 4)]
    plt.rcParams['savefig.dpi'] = 300
    # =========================================================================
    # Create the figure and an axes set to the projection.
    fig = plt.figure(figsize=(20, 16))
    ax = fig.add_subplot(1, 1, 1, projection=proj)
    if area == 'Antarctica':
        df = df.loc[df['latitude'] < north]
        ax.set_extent([-180, 180, -90, -60], ccrs.PlateCarree())
        theta = np.linspace(0, 2 * np.pi, 100)
        center, radius = [0.5, 0.5], 0.5
        verts = np.vstack([np.sin(theta), np.cos(theta)]).T
        circle = mpath.Path(verts * radius + center)
        ax.set_boundary(circle, transform=ax.transAxes)
    elif area == 'Arctic':
        df = df.loc[df['latitude'] > south]
        ax.set_extent([-180, 180, 60, 90], ccrs.PlateCarree())
        theta = np.linspace(0, 2 * np.pi, 100)
        center, radius = [0.5, 0.5], 0.5
        verts = np.vstack([np.sin(theta), np.cos(theta)]).T
        circle = mpath.Path(verts * radius + center)
        ax.set_boundary(circle, transform=ax.transAxes)

    else:
        ax.set_extent((west, east, south, north))

    # Get the wind components, converting from m/s to knots as will
    # be appropriate for the station plot.
    df['dd'][df['dd'] > 360] = np.nan
    u, v = wind_components(df['ff'].values * units('knots'),
                           df['dd'].values * units('deg'))
    cloud_frac = df['cloud_cover']
    # Change the DPI of the resulting figure. Higher DPI drastically improves
    # look of the text rendering.

    # Set up a cartopy feature for state borders.
    # state_boundaries = feat.NaturalEarthFeature(category='cultural',
    #                                             name='admin_0_countries',
    #                                             scale='10m',
    #                                             facecolor='#d8dcd6',
    #                                             alpha=0.5)
    # ax.coastlines(resolution='10m', zorder=0, color='black')
    # ax.add_feature(feat.LAND)
    ax.add_feature(feat.COASTLINE.with_scale('10m'),
                   zorder=2,
                   edgecolor='black')
    ax.add_feature(feat.OCEAN.with_scale('50m'), zorder=0)
    ax.add_feature(feat.STATES.with_scale('10m'),
                   zorder=1,
                   facecolor='white',
                   edgecolor='#5e819d')
    # ax.add_feature(cartopy.feature.OCEAN, zorder=0)
    # Set plot bounds

    # Start the station plot by specifying the axes to draw on, as well as the
    # lon/lat of the stations (with transform). We also the fontsize to 12 pt.
    stationplot = StationPlot(ax,
                              df['longitude'].values,
                              df['latitude'].values,
                              clip_on=True,
                              transform=ccrs.PlateCarree(),
                              fontsize=fonts)
    # Plot the temperature and dew point to the upper and lower left,
    # respectively, of the center point. Each one uses a different color.
    Temp = stationplot.plot_parameter('NW',
                                      df['TT'],
                                      color='#fd3c06',
                                      fontweight='bold',
                                      zorder=3)
    Td = stationplot.plot_parameter('SW', df['TD'], color='#01ff07')

    if gust == True:
        maxff = stationplot.plot_parameter('SE',
                                           df['max_gust'],
                                           color='#cb416b',
                                           fontweight='bold',
                                           zorder=3)
        maxff.set_path_effects([
            path_effects.Stroke(linewidth=1.5, foreground='black'),
            path_effects.Normal()
        ])
    # fontweight = 'bold'
    # More complex ex. uses custom formatter to control how sea-level pressure
    # values are plotted. This uses the standard trailing 3-digits of
    # the pressure value in tenths of millibars.

    if (area != 'Antarctica' and area != 'Arctic'):
        p = stationplot.plot_parameter(
            'NE',
            df['SLP'],
            formatter=lambda v: format(10 * v, '.0f')[-3:],
            color="#a2cffe")
        for x in [Temp, Td, p]:
            x.set_path_effects([
                path_effects.Stroke(linewidth=1.5, foreground='black'),
                path_effects.Normal()
            ])
    else:
        for x in [Temp, Td]:
            x.set_path_effects([
                path_effects.Stroke(linewidth=1.5, foreground='black'),
                path_effects.Normal()
            ])

    # Add wind barbs
    stationplot.plot_barb(u, v, zorder=3, linewidth=2)
    # Plot the cloud cover symbols in the center location. This uses the codes
    # made above and uses the `sky_cover` mapper to convert these values to
    # font codes for the weather symbol font.
    stationplot.plot_symbol('C', cloud_frac, sky_cover)
    # Same this time, but plot current weather to the left of center, using the
    # `current_weather` mapper to convert symbols to the right glyphs.
    for val in range(0, 2):
        wx = df[['ww', 'StationType']]
        if val == 0:
            # mask all the unmanned stations
            wx['ww'].loc[wx['StationType'] > 3] = np.nan
            wx2 = wx['ww'].fillna(00).astype(int).values.tolist()
            stationplot.plot_symbol('W', wx2, current_weather, zorder=4)
        else:
            # mask all the manned stations
            wx['ww'].loc[(wx['StationType'] <= 3)] = np.nan
            # mask all reports smaller than 9
            # =7 is an empty symbol!
            wx['ww'].loc[wx['ww'] <= 9] = 7
            wx2 = wx['ww'].fillna(7).astype(int).values.tolist()
            stationplot.plot_symbol('W', wx2, current_weather_auto, zorder=4)
    if SLP == True:
        lon = df['longitude'].loc[(df.PressureDefId == 'mean sea level')
                                  & (df.Hp <= 750)].values
        lat = df['latitude'].loc[(df.PressureDefId == 'mean sea level')
                                 & (df.Hp <= 750)].values
        xp, yp, _ = proj.transform_points(ccrs.PlateCarree(), lon, lat).T
        sea_levelp = df['SLP'].loc[(df.PressureDefId == 'mean sea level')
                                   & (df.Hp <= 750)]
        x_masked, y_masked, pres = remove_nan_observations(
            xp, yp, sea_levelp.values)
        slpgridx, slpgridy, slp = interpolate_to_grid(x_masked,
                                                      y_masked,
                                                      pres,
                                                      interp_type='cressman',
                                                      search_radius=400000,
                                                      rbf_func='quintic',
                                                      minimum_neighbors=1,
                                                      hres=100000,
                                                      rbf_smooth=100000)
        Splot_main = ax.contour(slpgridx,
                                slpgridy,
                                slp,
                                colors='k',
                                linewidths=2,
                                extent=(west, east, south, north),
                                levels=list(range(950, 1050, 10)))
        plt.clabel(Splot_main, inline=1, fontsize=12, fmt='%i')

        Splot = ax.contour(slpgridx,
                           slpgridy,
                           slp,
                           colors='k',
                           linewidths=1,
                           linestyles='--',
                           extent=(west, east, south, north),
                           levels=[
                               x for x in range(950, 1050, 1)
                               if x not in list(range(950, 1050, 10))
                           ])
        plt.clabel(Splot, inline=1, fontsize=10, fmt='%i')

    # stationplot.plot_text((2, 0), df['Station'])
    # Also plot the actual text of the station id. Instead of cardinal
    # directions, plot further out by specifying a location of 2 increments
    # in x and 0 in y.stationplot.plot_text((2, 0), df['station'])

    if (area == 'Antarctica' or area == 'Arctic'):
        plt.savefig(path + '/CURR_SYNOP_' + area + '.png',
                    bbox_inches='tight',
                    pad_inches=0)
    else:
        plt.savefig(path + '/CURR_SYNOP_' + area + '.png',
                    bbox_inches='tight',
                    transparent="True",
                    pad_inches=0)
Exemplo n.º 11
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib
matplotlib.rcParams['toolbar'] = 'None'
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
import matplotlib.patheffects as PathEffects

verts = [(45, 96), (262, 130), (268, 66), (33, 191)]
codes = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]

size = 256, 256
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi, facecolor="white")

axes = fig.add_axes([0.0, 0.0, 1.0, 1.0], frameon=False)
axes.set_xlim(0, size[0])
axes.set_ylim(0, size[1])

path = Path(verts, codes)
patch = patches.PathPatch(path, facecolor='none', lw=50, alpha=0.5)
patch.set_path_effects([PathEffects.Stroke(capstyle='round')])
axes.add_patch(patch)

plt.xticks([]), plt.yticks([])
fig.savefig('agg-bezier-2.png', dpi=dpi)
plt.show()
Exemplo n.º 12
0
        x_contour[0],
        y_contour[0],
        label=promoter,
        linewidth=1.0,
        c=cmap(
            col_norm(df_energies[df_energies.Name == promoter]
                     ["Energy (kT)"].values[0])),
    )
    text = ax_c.annotate(f"{i + 1}", (
        np.mean(x_contour[0]),
        np.mean(y_contour),
    ),
                         fontsize=7,
                         color="white")
    text.set_path_effects([
        path_effects.Stroke(linewidth=1.5, foreground="black"),
        path_effects.Normal()
    ])

ax_c.set_xlim(right=1.2e1)
ax_c.set_ylim(top=1e1)
ax_c.set_ylabel(r'$k_i$ (bursts per mRNA lifetime)')
ax_c.set_xlabel(r'$b$ (transcripts per burst)')

# (D)
# Add gridlines
[ax_d.axhline(x, color="white", linewidth=0.5) for x in [0.1, 1]]

# initialize lsit to save y position
y_pos = list()
for i, promoter in enumerate(df_energies.Name):
Exemplo n.º 13
0
    if len(fixation_intervals) > 0:

        avg_times.append(tmid)
        avg_dts.append(numpy.median(fixation_intervals))

        upper_dts.append(
            numpy.percentile(fixation_intervals, 75, interpolation='nearest'))
        lower_dts.append(
            numpy.percentile(fixation_intervals, 25, interpolation='nearest'))

fixation_time_axis.plot(
    avg_times,
    avg_dts,
    'w-',
    linewidth=1,
    path_effects=[pe.Stroke(linewidth=2.5, foreground='k'),
                  pe.Normal()])

fixation_time_axis.fill_between(avg_times, lower_dts, upper_dts, color='0.8')
fixation_time_axis.plot(avg_times, lower_dts, 'k-', linewidth=0.25)
fixation_time_axis.plot(avg_times, upper_dts, 'k-', linewidth=0.25)

######
#
# Now do fixation trajectories
#
########

theory_times = numpy.arange(0, 121) * 500
total_Mfixeds = numpy.zeros_like(theory_times) * 1.0
Exemplo n.º 14
0
    def movie(self, scale='linear', text=False, **kwargs):
        '''Create a movie of a populated array'''
        log.debug('Creating movie')
        start = time.time()
        # If there's not a lot of movement the movie should be fixed
        fig = plt.figure(figsize=(4, 4))
        ax = fig.add_subplot(111)
        plt.subplots_adjust(hspace=0, wspace=0)
        ax.set_facecolor('red')
        dat = (self.ar)
        if scale == 'log':
            dat = np.log10(self.ar)
        if 'vmin' not in kwargs:
            # Calculate color stretch...
            y = dat.ravel()
            y = y[np.isfinite(y)]
            y = y[y != 0]
            kwargs['vmin'] = np.percentile(y, 10)
            kwargs['vmax'] = np.percentile(y, 90)

        im = ax.imshow(dat[:, :, 0].T, **kwargs)
        ax.axis('off')
        if text:
            if self.name is not None:
                text1 = ax.text(0.1,
                                0.9,
                                self.name,
                                fontsize=10,
                                color='white',
                                transform=ax.transAxes)
                text1.set_path_effects([
                    path_effects.Stroke(linewidth=2, foreground='black'),
                    path_effects.Normal()
                ])
            text2 = ax.text(0.1,
                            0.83,
                            'Campaign {}'.format(self.campaign),
                            fontsize=8,
                            color='white',
                            transform=ax.transAxes)
            text2.set_path_effects([
                path_effects.Stroke(linewidth=2, foreground='black'),
                path_effects.Normal()
            ])
            text3 = ax.text(0.1,
                            0.78,
                            'Cadence: {}'.format(int(self.cadence_names[0])),
                            fontsize=8,
                            color='white',
                            transform=ax.transAxes)
            text3.set_path_effects([
                path_effects.Stroke(linewidth=2, foreground='black'),
                path_effects.Normal()
            ])

        def animate(i):
            im.set_array(dat[:, :, i].T)
            if text:
                text3.set_text('Cadence: {}'.format(int(
                    self.cadence_names[i])))
                return im, text3,
            return im,

        anim = animation.FuncAnimation(fig,
                                       animate,
                                       frames=len(self.cadence_names),
                                       interval=30,
                                       blit=True)
        anim.save(self.output, dpi=150)
        log.debug('Saved. ({0:0.2g}s)'.format(time.time() - start))
        plt.close()
cf = iplt.pcolormesh(scs, axes=axgr[0], cmap=gustcmap, norm=norm)
iplt.pcolormesh(vscs, axes=axgr[1], cmap=gustcmap, norm=norm)
iplt.pcolormesh(sscs, axes=axgr[2], cmap=gustcmap, norm=norm)

# Plot place labels
for ax in axgr:
    ax.plot(pop['LONGITUDE'].values,
            pop['LATITUDE'].values,
            marker='o',
            fillstyle='none',
            markersize=5,
            linestyle='none',
            color='black',
            path_effects=[
                path_effects.Stroke(linewidth=2, foreground='white'),
                path_effects.Normal()
            ])
    geodetic_transform = ccrs.PlateCarree()._as_mpl_transform(ax)
    for i, row, in pop.iterrows():
        if row['NAMEASCII'] in ['Dhaka', 'Saidpur', 'Jamalpur']:
            text = ax.text(row['LONGITUDE'],
                           row['LATITUDE'],
                           row['NAMEASCII'],
                           ha='right',
                           fontsize=8,
                           transform=offset_copy(geodetic_transform,
                                                 units='dots',
                                                 x=-4,
                                                 y=4))
            text.set_path_effects([
Exemplo n.º 16
0
    def __init__(
        self,
        line: Line2D,
        x: Position,
        label: str | None = None,
        align: bool = True,
        yoffset: float = 0,
        yoffset_logspace: bool = False,
        outline_color: AutoLiteral | ColorLike | None = "auto",
        outline_width: float = 8,
        **kwargs,
    ) -> None:
        """

        Parameters
        ----------
        line : Line2D
            Line to be decorated.
        x : Position
            Horizontal target position for the label (in data units).
        label : str, optional
            Override for line label, by default None.
        align : bool, optional
            If true, the label is parallel to the line, otherwise horizontal,
            by default True.
        yoffset : float, optional
            An additional y offset for the line label, by default 0.
        yoffset_logspace : bool, optional
            If true yoffset is applied exponentially to appear linear on a log-axis,
            by default False.
        outline_color : None | "auto" | Colorlike
            Colour of the outline. If set to "auto", use the background color.
            If set to None, do not draw an outline, by default "auto".
        outline_width : float
            Width of the outline, by default 8.
        """
        self._line = line
        self._target_x = x
        self._ax = line.axes
        self._auto_align = align
        self._yoffset = yoffset
        self._yoffset_logspace = yoffset_logspace
        label = label or line.get_label()

        # Populate self._pos, self._anchor_a, self._anchor_b
        self._update_anchors()

        # Set a bunch of default arguments
        kwargs.setdefault("color", self._line.get_color())
        kwargs.setdefault("clip_on", True)
        kwargs.setdefault("zorder", 2.5)
        if "ha" not in kwargs:
            kwargs.setdefault("horizontalalignment", "center")
        if "va" not in kwargs:
            kwargs.setdefault("verticalalignment", "center")

        # Initialize Text Artist
        super().__init__(
            *self._label_pos,
            label,
            rotation=self._rotation,
            rotation_mode="anchor",
            **kwargs,
        )

        # Apply outline effect
        if outline_color is not None:

            if outline_color == "auto":
                outline_color = line.axes.get_facecolor()

            self.set_path_effects([
                patheffects.Stroke(linewidth=outline_width,
                                   foreground=outline_color),
                patheffects.Normal(),
            ])

        # activate clipping if needed and place on axes
        if kwargs["clip_on"]:
            self.set_clip_path(self._ax.patch)
        self._ax._add_text(self)
Exemplo n.º 17
0
#-*- coding: utf-8 -*

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects
import seaborn as sns

x = [3.5, 9.2, 11.7, 24.1, 49.1]
y = [
    u"Nuestra\nImplementación", u"HomographyNet\n(Regresión)",
    u"ORB\n+\nRANSAC", u"HomographyNet\n(Clasificación)",
    u"Homografía\nIdentidad"
]
ax = sns.barplot(y, x, palette="Blues")
ax.set(ylabel="Mean Average Corner Error\n(pixels)")
for i, rect in enumerate(ax.patches):
    txt = ax.text(rect.get_x() + rect.get_width() / 2.0 -
                  len(str(x[i])) * 0.05,
                  rect.get_height() - 2.75 - rect.get_height() * 0.05,
                  x[i],
                  fontsize=20,
                  color='white')
    txt.set_path_effects([
        path_effects.Stroke(linewidth=2, foreground="gray"),
        path_effects.Normal()
    ])

plt.xticks(rotation=30)
plt.tight_layout()
plt.show()
Exemplo n.º 18
0
    def _render_on_subplot(self, subplot):
        r"""
        Render this arrow in a subplot.  This is the key function that
        defines how this arrow graphics primitive is rendered in
        matplotlib's library.

        EXAMPLES:

        This function implicitly ends up rendering this arrow on
        a matplotlib subplot::

            sage: arrow((0,1), (2,-1))
            Graphics object consisting of 1 graphics primitive

        TESTS:

        The length of the ends (shrinkA and shrinkB) should not depend
        on the width of the arrow, because Matplotlib already takes
        this into account. See :trac:`12836`::

            sage: fig = Graphics().matplotlib()
            sage: sp = fig.add_subplot(1,1,1)
            sage: a = arrow((0,0), (1,1))
            sage: b = arrow((0,0), (1,1), width=20)
            sage: p1 = a[0]._render_on_subplot(sp)
            sage: p2 = b[0]._render_on_subplot(sp)
            sage: p1.shrinkA == p2.shrinkA
            True
            sage: p1.shrinkB == p2.shrinkB
            True

        Dashed arrows should have solid arrowheads,
        :trac:`12852`. This test saves the plot of a dashed arrow to
        an EPS file. Within the EPS file, ``stroke`` will be called
        twice: once to draw the line, and again to draw the
        arrowhead. We check that both calls do not occur while the
        dashed line style is enabled::

            sage: a = arrow((0,0), (1,1), linestyle='dashed')
            sage: filename = tmp_filename(ext='.eps')
            sage: a.save(filename=filename)
            sage: with open(filename, 'r') as f:
            ....:     contents = f.read().replace('\n', ' ')
            sage: two_stroke_pattern = r'setdash.*stroke.*stroke.*setdash'
            sage: import re
            sage: two_stroke_re = re.compile(two_stroke_pattern)
            sage: two_stroke_re.search(contents) is None
            True
        """
        from sage.plot.misc import get_matplotlib_linestyle

        options = self.options()
        head = options.pop('head')
        if head == 0: style = '<|-'
        elif head == 1: style = '-|>'
        elif head == 2: style = '<|-|>'
        else:
            raise KeyError(
                'head parameter must be one of 0 (start), 1 (end) or 2 (both).'
            )
        width = float(options['width'])
        arrowshorten_end = float(options.get('arrowshorten', 0)) / 2.0
        arrowsize = float(options.get('arrowsize', 5))
        head_width = arrowsize
        head_length = arrowsize * 2.0
        color = to_mpl_color(options['rgbcolor'])
        from matplotlib.patches import FancyArrowPatch
        p = FancyArrowPatch((self.xtail, self.ytail), (self.xhead, self.yhead),
                            lw=width,
                            arrowstyle='%s,head_width=%s,head_length=%s' %
                            (style, head_width, head_length),
                            shrinkA=arrowshorten_end,
                            shrinkB=arrowshorten_end,
                            fc=color,
                            ec=color)
        p.set_linestyle(
            get_matplotlib_linestyle(options['linestyle'], return_type='long'))
        p.set_zorder(options['zorder'])
        p.set_label(options['legend_label'])

        if options['linestyle'] != 'solid':
            # The next few lines work around a design issue in matplotlib. Currently, the specified
            # linestyle is used to draw both the path and the arrowhead.  If linestyle is 'dashed', this
            # looks really odd.  This code is from Jae-Joon Lee in response to a post to the matplotlib mailing
            # list.  See http://sourceforge.net/mailarchive/forum.php?thread_name=CAG%3DuJ%2Bnw2dE05P9TOXTz_zp-mGP3cY801vMH7yt6vgP9_WzU8w%40mail.gmail.com&forum_name=matplotlib-users

            import matplotlib.patheffects as pe

            class CheckNthSubPath(object):
                def __init__(self, patch, n):
                    """
                    creates an callable object that returns True if the provided
                    path is the n-th path from the patch.
                    """
                    self._patch = patch
                    self._n = n

                def get_paths(self, renderer):
                    self._patch.set_dpi_cor(renderer.points_to_pixels(1.))
                    paths, fillables = self._patch.get_path_in_displaycoord()
                    return paths

                def __call__(self, renderer, gc, tpath, affine, rgbFace):
                    path = self.get_paths(renderer)[self._n]
                    vert1, code1 = path.vertices, path.codes
                    import numpy as np

                    if np.all(vert1 == tpath.vertices) and np.all(
                            code1 == tpath.codes):
                        return True
                    else:
                        return False

            class ConditionalStroke(pe.RendererBase):
                def __init__(self, condition_func, pe_list):
                    """
                    path effect that is only applied when the condition_func
                    returns True.
                    """
                    super(ConditionalStroke, self).__init__()
                    self._pe_list = pe_list
                    self._condition_func = condition_func

                def draw_path(self, renderer, gc, tpath, affine, rgbFace):

                    if self._condition_func(renderer, gc, tpath, affine,
                                            rgbFace):
                        for pe1 in self._pe_list:
                            pe1.draw_path(renderer, gc, tpath, affine, rgbFace)

            pe1 = ConditionalStroke(CheckNthSubPath(p, 0), [pe.Stroke()])
            pe2 = ConditionalStroke(CheckNthSubPath(p, 1),
                                    [pe.Stroke(linestyle="solid")])
            p.set_path_effects([pe1, pe2])

        subplot.add_patch(p)
        return p
Exemplo n.º 19
0
def draw_mslp_gust10m_uv10m(gust=None,
                            mslp=None,
                            uv10m=None,
                            map_extent=(50, 150, 0, 65),
                            regrid_shape=20,
                            add_china=True,
                            city=True,
                            south_China_sea=True,
                            output_dir=None,
                            Global=False):

    # set font
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    # set figure
    plt.figure(figsize=(16, 9))

    if (Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(
            central_latitude=(map_extent[2] + map_extent[3]) / 2.,
            central_longitude=(map_extent[0] + map_extent[1]) / 2.,
            standard_parallels=[30., 60.])

    datacrs = ccrs.PlateCarree()
    ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs)
    map_extent2 = utl.adjust_map_ratio(ax,
                                       map_extent=map_extent,
                                       datacrs=datacrs)

    #draw data
    plots = {}
    if gust is not None:
        x, y = np.meshgrid(gust['lon'], gust['lat'])
        z = np.squeeze(gust['data'].values)
        cmap = dk_ctables.cm_wind_speed_nws()
        cmap.set_under(color=[0, 0, 0, 0], alpha=0.0)
        z[z < 7.9] = np.nan
        plots['gust'] = ax.pcolormesh(x,
                                      y,
                                      z,
                                      cmap=cmap,
                                      vmin=7.9,
                                      vmax=65,
                                      zorder=1,
                                      transform=datacrs,
                                      alpha=0.5)

    ax.quiver(x,
              y,
              np.squeeze(uv10m['u10m'].values),
              np.squeeze(uv10m['v10m'].values),
              transform=datacrs,
              regrid_shape=40,
              width=0.001)

    if mslp is not None:
        x, y = np.meshgrid(mslp['lon'], mslp['lat'])
        clevs_mslp = np.arange(900, 1100, 2.5)
        z = gaussian_filter(np.squeeze(mslp['data']), 5)
        plots['mslp'] = ax.contour(x,
                                   y,
                                   z,
                                   clevs_mslp,
                                   colors='black',
                                   linewidths=1,
                                   transform=datacrs,
                                   zorder=2,
                                   alpha=0.5)
        cl = plt.clabel(plots['mslp'],
                        inline=1,
                        fontsize=15,
                        fmt='%.1f',
                        colors='black')
        for t in cl:
            t.set_path_effects([
                mpatheffects.Stroke(linewidth=3, foreground='white'),
                mpatheffects.Normal()
            ])


#additional information
    plt.title('[' + mslp.attrs['model'] + '] ' + '海平面气压, ' + '逐' +
              '%i' % gust.attrs['t_gap'] + '小时10米最大阵风和10米平均风',
              loc='left',
              fontsize=30)

    utl.add_china_map_2cartopy_public(ax,
                                      name='coastline',
                                      edgecolor='gray',
                                      lw=0.8,
                                      zorder=3,
                                      alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(ax,
                                          name='province',
                                          edgecolor='gray',
                                          lw=0.5,
                                          zorder=3)
        utl.add_china_map_2cartopy_public(ax,
                                          name='nation',
                                          edgecolor='black',
                                          lw=0.8,
                                          zorder=3)
        utl.add_china_map_2cartopy_public(ax,
                                          name='river',
                                          edgecolor='#74b9ff',
                                          lw=0.8,
                                          zorder=3,
                                          alpha=0.5)

    # grid lines
    gl = ax.gridlines(crs=datacrs,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--',
                      zorder=4)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    #utl.add_cartopy_background(ax,name='RD')
    ax.add_feature(cfeature.LAND, color='#F5E19F')
    ax.add_feature(cfeature.OCEAN)

    l, b, w, h = ax.get_position().bounds

    #forecast information
    bax = plt.axes([l, b + h - 0.1, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(
        str(mslp.coords['forecast_reference_time'].values)).replace(
            tzinfo=None).to_pydatetime()
    fcst_time = initTime + timedelta(
        hours=mslp.coords['forecast_period'].values[0])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5, 5, '预报时间: ' + fcst_time.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5,
             2.5,
             '预报时效: ' + str(int(mslp.coords['forecast_period'].values[0])) +
             '小时',
             size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add color bar
    if (gust != None):
        cax = plt.axes([l, b - 0.04, w, .02])
        cb = plt.colorbar(plots['gust'],
                          cax=cax,
                          orientation='horizontal',
                          extend='max',
                          ticks=[
                              8.0, 10.8, 13.9, 17.2, 20.8, 24.5, 28.5, 32.7,
                              37, 41.5, 46.2, 51.0, 56.1, 61.3
                          ])
        cb.ax.tick_params(labelsize='x-large')
        cb.set_label('风速 (m/s)', size=20)

    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[l + w - 0.091, b, .1, .2])

    small_city = False
    if (map_extent2[1] - map_extent2[0] < 25):
        small_city = True
    if city:
        utl.add_city_on_map(ax,
                            map_extent=map_extent2,
                            transform=datacrs,
                            zorder=5,
                            size=13,
                            small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[l - 0.02, b + h - 0.1, .1, .1],
                               which='nmc',
                               size='Xlarge')

    # show figure
    if (output_dir != None):
        plt.savefig(output_dir + '海平面气压_逐6小时最大风速_预报_' + '起报时间_' +
                    initTime.strftime("%Y年%m月%d日%H时") + '预报时效_' +
                    str(mslp.coords['forecast_period'].values[0]) + '小时' +
                    '.png',
                    dpi=200)

    if (output_dir == None):
        plt.show()
Exemplo n.º 20
0
def plot_animation(clip,
                   parents,
                   filename=None,
                   fps=30,
                   axis_scale=50,
                   elev=45,
                   azim=45):

    rot = R.from_quat([0, 0, 0, 1])
    translation = np.array([[0, 0, 0]])
    translations = np.zeros((clip.shape[0], 3))

    joints, root_dx, root_dz, root_dr = clip[:, :
                                             -3], clip[:,
                                                       -3], clip[:,
                                                                 -2], clip[:,
                                                                           -1]
    joints = joints.reshape((len(joints), -1, 3))
    for i in range(len(joints)):
        joints[i, :, :] = rot.apply(joints[i])
        joints[i, :, 0] = joints[i, :, 0] + translation[0, 0]
        joints[i, :, 2] = joints[i, :, 2] + translation[0, 2]
        rot = R.from_rotvec(np.array([0, -root_dr[i], 0])) * rot
        translation = translation + rot.apply(
            np.array([root_dx[i], 0, root_dz[i]]))
        translations[i, :] = translation

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111, projection='3d')
    ax.set_xlim3d(-axis_scale, axis_scale)
    ax.set_zlim3d(0, axis_scale)
    ax.set_ylim3d(-axis_scale, axis_scale)
    ax.grid(True)
    ax.set_axis_off()

    ax.view_init(elev=elev, azim=azim)

    xs = np.linspace(-200, 200, 50)
    ys = np.linspace(-200, 200, 50)
    X, Y = np.meshgrid(xs, ys)
    Z = np.zeros(X.shape)

    wframe = ax.plot_wireframe(X,
                               Y,
                               Z,
                               rstride=2,
                               cstride=2,
                               color='grey',
                               lw=0.2)

    points = []
    lines = []
    acolors = list(sorted(colors.cnames.keys()))[::-1]
    tmp = np.zeros(translations.shape)
    lines.append(
        plt.plot(translations[:, 0],
                 -translations[:, 2],
                 lw=2,
                 path_effects=[
                     pe.Stroke(linewidth=1, foreground='black'),
                     pe.Normal()
                 ])[0])
    lines.append([
        plt.plot([0, 0], [0, 0], [0, 0],
                 color='red',
                 lw=2,
                 path_effects=[
                     pe.Stroke(linewidth=3, foreground='black'),
                     pe.Normal()
                 ])[0] for _ in range(joints.shape[1])
    ])

    def animate(i):

        changed = []

        for j in range(len(parents)):
            if parents[j] != -1:
                lines[1][j].set_data(
                    np.array([[joints[i, j, 0], joints[i, parents[j], 0]],
                              [-joints[i, j, 2], -joints[i, parents[j], 2]]]))
                lines[1][j].set_3d_properties(
                    np.array([joints[i, j, 1], joints[i, parents[j], 1]]))

        changed += lines

        return changed

    plt.tight_layout()

    ani = animation.FuncAnimation(fig,
                                  animate,
                                  np.arange(joints.shape[0]),
                                  interval=1000 / fps)

    if filename != None:
        ani.save(filename, fps=fps, bitrate=13934)
        ani.event_source.stop()
        del ani
        plt.close()
    try:
        plt.show()
        plt.save()
    except AttributeError as e:
        pass
Exemplo n.º 21
0
    def draw(self):
        # In order to speed up the plotting, we only recalculate everything
        # if necessary.
        self.IntRegionLines = []
        # Figure out the color and ylabel
        # Choose the particle type and px, py, or pz
        self.UpdateLabelsandColors()

        self.xmin = self.hist2d[2][0]
        self.xmax = self.hist2d[2][-1]

        self.ymin = self.hist2d[1][0]
        self.ymax = self.hist2d[1][-1]

        if self.GetPlotParam('masked'):
            self.tick_color = 'k'
        else:
            self.tick_color = 'white'

        self.clim = list(self.hist2d[3])

        if self.GetPlotParam('set_v_min'):
            self.clim[0] = 10**self.GetPlotParam('v_min')
        if self.GetPlotParam('set_v_max'):
            self.clim[1] = 10**self.GetPlotParam('v_max')

        self.gs = gridspec.GridSpecFromSubplotSpec(
            100, 100, subplot_spec=self.parent.gs0[
                self.pos])  #, bottom=0.2,left=0.1,right=0.95, top = 0.95)

        self.axes = self.figure.add_subplot(
            self.gs[self.parent.axes_extent[0]:self.parent.axes_extent[1],
                    self.parent.axes_extent[2]:self.parent.axes_extent[3]])

        self.cax = self.axes.imshow(
            self.hist2d[0],
            cmap=new_cmaps.cmaps[self.parent.MainParamDict['ColorMap']],
            norm=self.norm(),
            origin='lower',
            aspect='auto',
            interpolation=self.GetPlotParam('interpolation'))

        self.cax.set_extent([self.xmin, self.xmax, self.ymin, self.ymax])

        self.cax.set_clim(self.clim)

        self.shock_line = self.axes.axvline(self.parent.shock_loc,
                                            linewidth=1.5,
                                            linestyle='--',
                                            color=self.parent.shock_color,
                                            path_effects=[
                                                PathEffects.Stroke(
                                                    linewidth=2,
                                                    foreground='k'),
                                                PathEffects.Normal()
                                            ])
        if not self.GetPlotParam('show_shock'):
            self.shock_line.set_visible(False)

        self.axC = self.figure.add_subplot(
            self.gs[self.parent.cbar_extent[0]:self.parent.cbar_extent[1],
                    self.parent.cbar_extent[2]:self.parent.cbar_extent[3]])

        # Technically I should use the colorbar class here,
        # but I found it annoying in some of it's limitations.
        if self.parent.MainParamDict['HorizontalCbars']:
            self.cbar = self.axC.imshow(
                self.gradient,
                aspect='auto',
                cmap=new_cmaps.cmaps[self.parent.MainParamDict['ColorMap']])
            # Make the colobar axis more like the real colorbar
            self.axC.tick_params(
                axis='x',
                which='both',  # bothe major and minor ticks
                top=False,  # turn off top ticks
                labelsize=self.parent.MainParamDict['NumFontSize'])

            self.axC.tick_params(
                axis='y',  # changes apply to the y-axis
                which='both',  # both major and minor ticks are affected
                left=False,  # ticks along the bottom edge are off
                right=False,  # ticks along the top edge are off
                labelleft=False)

        else:
            self.cbar = self.axC.imshow(
                np.transpose(self.gradient)[::-1],
                aspect='auto',
                origin='upper',
                cmap=new_cmaps.cmaps[self.parent.MainParamDict['ColorMap']])
            # Make the colobar axis more like the real colorbar
            self.axC.tick_params(
                axis='x',
                which='both',  # bothe major and minor ticks
                top=False,  # turn off top ticks
                bottom=False,
                labelbottom=False,
                labelsize=self.parent.MainParamDict['NumFontSize'])

            self.axC.tick_params(
                axis='y',  # changes apply to the y-axis
                which='both',  # both major and minor ticks are affected
                left=False,  # ticks along the bottom edge are off
                right=True,  # ticks along the top edge are off
                labelleft=False,
                labelright=True,
                labelsize=self.parent.MainParamDict['NumFontSize'])

        self.cbar.set_extent([0, 1.0, 0, 1.0])

        if not self.GetPlotParam('show_cbar'):
            self.axC.set_visible(False)

        if int(matplotlib.__version__[0]) < 2:
            self.axes.set_axis_bgcolor(self.GetPlotParam('face_color'))
        else:
            self.axes.set_facecolor(self.GetPlotParam('face_color'))
        self.axes.tick_params(
            labelsize=self.parent.MainParamDict['NumFontSize'],
            color=self.tick_color)
        self.axes.set_xlabel(self.x_label,
                             labelpad=self.parent.MainParamDict['xLabelPad'],
                             color='black',
                             size=self.parent.MainParamDict['AxLabelSize'])
        self.axes.set_ylabel(self.y_label,
                             labelpad=self.parent.MainParamDict['yLabelPad'],
                             color='black',
                             size=self.parent.MainParamDict['AxLabelSize'])

        self.refresh()
    ##############################################################################
    ## affichage de la localisation des déviation en fonction des composants

    std = np.sqrt(pca.explained_variance_)

    ##############################################################################
    # plot the mean and the different axes of the PCA

    ax1.plot(
        fCDF,
        pca.mean_,
        c='C0',
        label='Mean',
        linewidth=2,
        zorder=10,
        path_effects=[pe.Stroke(linewidth=4, foreground='w'),
                      pe.Normal()])
    # Transform the axes points into curves
    y = pca.inverse_transform([std[0], 0])
    ax1.plot(
        fCDF,
        y,
        'g',
        label='1st component [+std]',
        linewidth=2,
        zorder=10,
        path_effects=[pe.Stroke(linewidth=4, foreground='w'),
                      pe.Normal()])
    y = pca.inverse_transform([-std[0], 0])
    ax1.plot(
        fCDF,
Exemplo n.º 23
0
    num = len(labels)
    names = dict()
    for i in range(10):
        names[i] = str(i)

    palette = np.array(sns.color_palette("hls", 10))
    f = plt.figure(figsize=(8, 8))
    ax = plt.subplot(aspect='equal')
    sc = ax.scatter(embeds[:, 0],
                    embeds[:, 1],
                    lw=0,
                    s=40,
                    c=palette[labels.astype(np.int)])
    ax.axis('off')
    ax.axis('tight')

    # We add the labels for each digit.
    txts = []
    for i in range(10):
        # Position of each label.
        xtext, ytext = np.median(embeds[labels == i, :], axis=0)
        txt = ax.text(xtext, ytext, names[i])
        txt.set_path_effects([
            PathEffects.Stroke(linewidth=5, foreground="w"),
            PathEffects.Normal()
        ])
        txts.append(txt)

    fname = 'mnist-sphereface-%d-epoch.png' % (epoch)
    plt.savefig(fname)
Exemplo n.º 24
0
ax2.xaxis.set_major_formatter(date_format_bf)
# plt.axhline(y=freq[stria_floc], color='r')
# plt.axvline(x=bf_dt_arr[stria_tloc], color='r')
ax2.set_xlabel("Time (UTC)", fontsize=14)
ax2.set_ylabel("Frequency (MHz)", fontsize=14)
ax2.set_yticklabels([*ax2.get_yticks()], fontsize=14)
text2 = ax2.text(0.05,
                 0.9,
                 'b) LOFAR Dynamic Spectrum',
                 fontdict={
                     'size': 14,
                     'color': 'w'
                 },
                 transform=ax2.transAxes)
text2.set_path_effects(
    [path_effects.Stroke(linewidth=1, foreground='k'),
     path_effects.Normal()])
#plt.tight_layout()
# fig.autofmt_xdate()

xy0 = v0.get_data()
xy0 = (xy0[0][0], xy0[1][0])
coords0 = gax.get_xaxis_transform()
con_axes0 = ConnectionPatch(xyA=xy0,
                            xyB=(0, 1),
                            coordsA=coords0,
                            coordsB="axes fraction",
                            axesA=gax,
                            axesB=ax2,
                            arrowstyle="-",
                            color="r")
Exemplo n.º 25
0
def draw_contour(shakegrid, popgrid, oceanfile, oceangridfile, cityfile, basename, borderfile=None, is_scenario=False):
    """Create a contour map showing population (greyscale) underneath contoured MMI.

    :param shakegrid:
      ShakeGrid object.
    :param popgrid:
      Grid2D object containing population data.
    :param oceanfile:
      String path to file containing ocean vector data in a format compatible with fiona.
    :param oceangridfile:
      String path to file containing ocean grid data .
    :param cityfile:
      String path to file containing GeoNames cities data.
    :param basename:
      String path containing desired output PDF base name, i.e., /home/pager/exposure.  ".pdf" and ".png" files will
      be made.
    :param make_png:
      Boolean indicating whether a PNG version of the file should also be created in the
      same output folder as the PDF.
    :returns:
      Tuple containing: 
        - Name of PNG file created, or None if PNG output not specified.
        - Cities object containing the cities that were rendered on the contour map.
    """
    gd = shakegrid.getGeoDict()

    # Retrieve the epicenter - this will get used on the map
    center_lat = shakegrid.getEventDict()['lat']
    center_lon = shakegrid.getEventDict()['lon']

    # load the ocean grid file (has 1s in ocean, 0s over land)
    # having this file saves us almost 30 seconds!
    oceangrid = GDALGrid.load(oceangridfile, samplegeodict=gd, resample=True)

    # load the cities data, limit to cities within shakemap bounds
    allcities = Cities.fromDefault()
    cities = allcities.limitByBounds((gd.xmin, gd.xmax, gd.ymin, gd.ymax))

    # define the map
    # first cope with stupid 180 meridian 
    height = (gd.ymax-gd.ymin)*111.191
    if gd.xmin < gd.xmax:
        width = (gd.xmax-gd.xmin)*np.cos(np.radians(center_lat))*111.191
        xmin, xmax, ymin, ymax = (gd.xmin, gd.xmax, gd.ymin, gd.ymax)
    else:
        xmin, xmax, ymin, ymax = (gd.xmin, gd.xmax, gd.ymin, gd.ymax)
        xmax += 360
        width = ((gd.xmax+360) - gd.xmin)*np.cos(np.radians(center_lat))*111.191

    aspect = width/height

    # if the aspect is not 1, then trim bounds in x or y direction as appropriate
    if width > height:
        dw = (width - height)/2.0  # this is width in km
        xmin = xmin + dw/(np.cos(np.radians(center_lat))*111.191)
        xmax = xmax - dw/(np.cos(np.radians(center_lat))*111.191)
        width = (xmax-xmin)*np.cos(np.radians(center_lat))*111.191
    if height > width:
        dh = (height - width)/2.0  # this is width in km
        ymin = ymin + dh/111.191
        ymax = ymax - dh/111.191
        height = (ymax-ymin)*111.191
        
    aspect = width/height
    figheight = FIGWIDTH/aspect
    bbox = (xmin, ymin, xmax, ymax)
    bounds = (xmin, xmax, ymin, ymax)
    figsize = (FIGWIDTH, figheight)

    # Create the MercatorMap object, which holds a separate but identical
    # axes object used to determine collisions between city labels.
    mmap = MercatorMap(bounds, figsize, cities, padding=0.5)
    fig = mmap.figure
    ax = mmap.axes
    # this needs to be done here so that city label collision detection will work
    fig.canvas.draw() 
    
    clon = xmin + (xmax-xmin)/2
    clat = ymin + (ymax-ymin)/2
    geoproj = mmap.geoproj
    proj = mmap.proj

    # project our population grid to the map projection
    projstr = proj.proj4_init
    popgrid_proj = popgrid.project(projstr)
    popdata = popgrid_proj.getData()
    newgd = popgrid_proj.getGeoDict()

    # Use our GMT-inspired palette class to create population and MMI colormaps 
    popmap = ColorPalette.fromPreset('pop')
    mmimap = ColorPalette.fromPreset('mmi')

    # set the image extent to that of the data
    img_extent = (newgd.xmin, newgd.xmax, newgd.ymin, newgd.ymax)
    plt.imshow(popdata, origin='upper', extent=img_extent, cmap=popmap.cmap,
               vmin=popmap.vmin, vmax=popmap.vmax, zorder=POP_ZORDER, interpolation='nearest')

    # draw 10m res coastlines
    ax.coastlines(resolution="10m", zorder=COAST_ZORDER);

    states_provinces = cfeature.NaturalEarthFeature(
        category='cultural',
        name='admin_1_states_provinces_lines',
        scale='50m',
        facecolor='none')

    ax.add_feature(states_provinces, edgecolor='black',zorder=COAST_ZORDER)
    
    # draw country borders using natural earth data set
    if borderfile is not None:
        borders = ShapelyFeature(Reader(borderfile).geometries(),
                                    ccrs.PlateCarree())
        ax.add_feature(borders, zorder=COAST_ZORDER, edgecolor='black', linewidth=2, facecolor='none')
    
    # clip the ocean data to the shakemap
    bbox = (gd.xmin, gd.ymin, gd.xmax, gd.ymax)
    oceanshapes = _clip_bounds(bbox, oceanfile)

    ax.add_feature(ShapelyFeature(oceanshapes, crs=geoproj), facecolor=WATERCOLOR, zorder=OCEAN_ZORDER)


    # It turns out that when presented with a map that crosses the 180 meridian,
    # the matplotlib/cartopy contouring routine thinks that the 180 meridian is a map boundary
    # and only plots one side of the contour.  Contouring the geographic MMI data and then
    # projecting the resulting contour vectors does the trick.  Sigh. 

    # define contour grid spacing
    contoury = np.linspace(ymin, ymax, gd.ny)
    contourx = np.linspace(xmin, xmax, gd.nx)

    # smooth the MMI data for contouring
    mmi = shakegrid.getLayer('mmi').getData()
    smoothed_mmi = gaussian_filter(mmi, FILTER_SMOOTH)

    # create masked arrays of the ocean grid
    landmask = np.ma.masked_where(oceangrid._data == 0.0, smoothed_mmi)
    oceanmask = np.ma.masked_where(oceangrid._data == 1.0, smoothed_mmi)

    # contour the data
    land_contour = plt.contour(contourx, contoury, np.flipud(oceanmask), linewidths=3.0, linestyles='solid',
                               zorder=LANDC_ZORDER, cmap=mmimap.cmap,
                               vmin=mmimap.vmin, vmax=mmimap.vmax,
                               levels=np.arange(0.5, 10.5, 1.0),
                               transform=geoproj)
    
    ocean_contour = plt.contour(contourx, contoury, np.flipud(landmask), linewidths=2.0, linestyles='dashed',
                                zorder=OCEANC_ZORDER, cmap=mmimap.cmap,
                                vmin=mmimap.vmin, vmax=mmimap.vmax,
                                levels=np.arange(0.5, 10.5, 1.0), transform=geoproj)
    
    # the idea here is to plot invisible MMI contours at integer levels and then label them.
    # clabel method won't allow text to appear, which is this case is kind of ok, because
    # it allows us an easy way to draw MMI labels as roman numerals.
    cs_land = plt.contour(contourx, contoury, np.flipud(oceanmask),
                          linewidths=0.0, levels=np.arange(0, 11),alpha=0.0,
                          zorder=CLABEL_ZORDER, transform=geoproj)
    
    clabel_text = ax.clabel(cs_land, np.arange(0, 11), colors='k', zorder=CLABEL_ZORDER, fmt='%.0f', fontsize=40)
    for clabel in clabel_text:
        x, y = clabel.get_position()
        label_str = clabel.get_text()
        roman_label = MMI_LABELS[label_str]
        th=plt.text(x, y, roman_label, zorder=CLABEL_ZORDER, ha='center',
                        va='center', color='black', weight='normal',
                        size=16)
        th.set_path_effects([path_effects.Stroke(linewidth=2.0, foreground='white'),
                             path_effects.Normal()])

    cs_ocean = plt.contour(contourx, contoury, np.flipud(landmask),
                          linewidths=0.0, levels=np.arange(0, 11),
                          zorder=CLABEL_ZORDER, transform=geoproj)
    
    clabel_text = ax.clabel(cs_ocean, np.arange(0, 11), colors='k', zorder=CLABEL_ZORDER, fmt='%.0f', fontsize=40)
    for clabel in clabel_text:
        x, y = clabel.get_position()
        label_str = clabel.get_text()
        roman_label = MMI_LABELS[label_str]
        th=plt.text(x, y, roman_label, zorder=CLABEL_ZORDER, ha='center',
                        va='center', color='black', weight='normal',
                        size=16)
        th.set_path_effects([path_effects.Stroke(linewidth=2.0, foreground='white'),
                             path_effects.Normal()])

    # draw meridians and parallels using Cartopy's functions for that
    gl = ax.gridlines(draw_labels=True,
                      linewidth=2, color=(0.9, 0.9, 0.9), alpha=0.5, linestyle='-',
                      zorder=GRID_ZORDER)
    gl.xlabels_top = False
    gl.xlabels_bottom = False
    gl.ylabels_left = False
    gl.ylabels_right = False
    gl.xlines = True
    step = 1

    # let's floor/ceil the edges to nearest half a degree
    gxmin = np.floor(xmin * 2) / 2
    gxmax = np.ceil(xmax * 2) / 2
    gymin = np.floor(ymin * 2) / 2
    gymax = np.ceil(ymax * 2) / 2

    xlocs = np.linspace(gxmin, gxmax+0.5, num=5)
    ylocs = np.linspace(gymin, gymax+0.5, num=5)
    
    gl.xlocator = mticker.FixedLocator(xlocs)
    gl.ylocator = mticker.FixedLocator(ylocs)
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    gl.xlabel_style = {'size': 15, 'color': 'black'}
    gl.ylabel_style = {'size': 15, 'color': 'black'}

    # TODO - figure out x/y axes data coordinates corresponding to 10% from left
    # and 10% from top
    # use geoproj and proj
    dleft = 0.01
    dtop = 0.97
    proj_str = proj.proj4_init
    merc_to_dd = pyproj.Proj(proj_str)

    # use built-in transforms to get from axes units to data units
    display_to_data = ax.transData.inverted()
    axes_to_display = ax.transAxes

    # these are x,y coordinates in projected space
    yleft, t1 = display_to_data.transform(axes_to_display.transform((dleft, 0.5)))
    t2, xtop = display_to_data.transform(axes_to_display.transform((0.5, dtop)))

    # these are coordinates in lon,lat space
    yleft_dd, t1_dd = merc_to_dd(yleft, t1, inverse=True)
    t2_dd, xtop_dd = merc_to_dd(t2, xtop, inverse=True)
    
    
    # drawing our own tick labels INSIDE the plot, as Cartopy doesn't seem to support this.
    yrange = ymax - ymin
    xrange = xmax - xmin
    ddlabelsize = 12
    for xloc in gl.xlocator.locs:
        outside = xloc < xmin or xloc > xmax
        # don't draw labels when we're too close to either edge
        near_edge = (xloc-xmin) < (xrange*0.1) or (xmax-xloc) < (xrange*0.1)
        if outside or near_edge:
            continue
        xtext = r'$%.1f^\circ$W' % (abs(xloc))
        ax.text(xloc, xtop_dd, xtext,
                fontsize=ddlabelsize, zorder=GRID_ZORDER, ha='center',
                fontname=DEFAULT_FONT,
                transform=ccrs.Geodetic())

    for yloc in gl.ylocator.locs:
        outside = yloc < gd.ymin or yloc > gd.ymax
        # don't draw labels when we're too close to either edge
        near_edge = (yloc-gd.ymin) < (yrange*0.1) or (gd.ymax-yloc) < (yrange*0.1)
        if outside or near_edge:
            continue
        if yloc < 0:
            ytext = r'$%.1f^\circ$S' % (abs(yloc))
        else:
            ytext = r'$%.1f^\circ$N' % (abs(yloc))
        thing = ax.text(yleft_dd, yloc, ytext,
                        fontsize=ddlabelsize, zorder=GRID_ZORDER, va='center',
                        fontname=DEFAULT_FONT,
                        transform=ccrs.Geodetic())


    # draw cities
    mapcities = mmap.drawCities(shadow=True, zorder=CITIES_ZORDER)


    # draw the figure border thickly
    # TODO - figure out how to draw map border
    # bwidth = 3
    # ax.spines['top'].set_visible(True)
    # ax.spines['left'].set_visible(True)
    # ax.spines['bottom'].set_visible(True)
    # ax.spines['right'].set_visible(True)
    # ax.spines['top'].set_linewidth(bwidth)
    # ax.spines['right'].set_linewidth(bwidth)
    # ax.spines['bottom'].set_linewidth(bwidth)
    # ax.spines['left'].set_linewidth(bwidth)
    
    # Get the corner of the map with the lowest population
    corner_rect, filled_corner = _get_open_corner(popgrid, ax)
    clat2 = round_to_nearest(center_lat, 1.0)
    clon2 = round_to_nearest(center_lon, 1.0)

    # draw a little globe in the corner showing in small-scale where the earthquake is located.
    # proj = ccrs.Orthographic(central_latitude=clat2,
    #                          central_longitude=clon2)
    # ax2 = fig.add_axes(corner_rect,projection=proj)
    # ax2.add_feature(cartopy.feature.OCEAN, zorder=0,facecolor=WATERCOLOR,edgecolor=WATERCOLOR)
    # ax2.add_feature(cartopy.feature.LAND, zorder=0, edgecolor='black')
    # ax2.plot([clon2],[clat2],'w*',linewidth=1,markersize=16,markeredgecolor='k',markerfacecolor='r')
    # gh=ax2.gridlines();
    # ax2.set_global();
    # ax2.outline_patch.set_edgecolor('black')
    # ax2.outline_patch.set_linewidth(2);

    # Draw the map scale in the unoccupied lower corner.
    corner = 'lr'
    if filled_corner == 'lr':
        corner = 'll'
    draw_scale(ax, corner, pady=0.05, padx=0.05)

    # Draw the epicenter as a black star
    plt.sca(ax)
    plt.plot(center_lon, center_lat, 'k*', markersize=16, zorder=EPICENTER_ZORDER, transform=geoproj)

    if is_scenario:
        plt.text(center_lon, center_lat, 'SCENARIO', fontsize=64,
                 zorder=WATERMARK_ZORDER, transform=geoproj,
                 alpha=0.2, color='red', horizontalalignment='center')
    
    # create pdf and png output file names
    pdf_file = basename+'.pdf'
    png_file = basename+'.png'
    
    # save to pdf
    plt.savefig(pdf_file)
    plt.savefig(png_file)
    
    return (pdf_file, png_file, mapcities)
    family="Lint McCree Intl BB",
)

# Title
# -----------------------------------------------------------------------------
textpath = TextPath((8, 80),
                    "MATPLOTLIB",
                    size=8,
                    prop=FontProperties(family="GlassJaw BB"))
patch = mpatches.PathPatch(textpath,
                           facecolor="none",
                           edgecolor="none",
                           zorder=5,
                           joinstyle="round")
patch.set_path_effects([
    path_effects.Stroke(linewidth=8, foreground="black"),
    path_effects.Stroke(linewidth=6, foreground="yellow"),
    path_effects.Stroke(linewidth=3, foreground="black"),
])

transform = ax.transData + mpl.transforms.Affine2D().rotate_deg(2.5)
patch.set_transform(transform)

ax.add_artist(patch)
Z = np.linspace(1, 0, 100).reshape(100, 1)
im = ax.imshow(Z, cmap="autumn", extent=[1, 100, 79, 87], zorder=15)
im.set_transform(transform)
im.set_clip_path(patch._path, patch.get_transform())

ax.text(
    47,
Exemplo n.º 27
0
def _draw_outline(o, lw):
    o.set_path_effects([
        patheffects.Stroke(linewidth=lw, foreground='black'),
        patheffects.Normal()
    ])
Exemplo n.º 28
0
def mslp_label(mslp, lat, lon):

    #Determine an appropriate window given the lat/lon grid resolution
    mslp = np.ma.masked_invalid(mslp)
    local_min, local_max = extrema(mslp, mode='wrap', window=50)

    #Determine axis boundaries
    xmin, xmax, ymin, ymax = ax.get_extent()
    lons2d, lats2d = np.meshgrid(lon, lat)
    transformed = proj.transform_points(ccrs.PlateCarree(), lons2d, lats2d)
    x = transformed[..., 0]
    y = transformed[..., 1]

    #Get location of extrema on grid
    xlows = x[local_min]
    xhighs = x[local_max]
    ylows = y[local_min]
    yhighs = y[local_max]
    lowvals = mslp[local_min]
    highvals = mslp[local_max]
    yoffset = 0.022 * (ymax - ymin)
    dmin = yoffset

    #Plot low pressures
    xyplotted = []
    for x, y, p in zip(xlows, ylows, lowvals):
        if x < xmax - yoffset and x > xmin + yoffset and y < ymax - yoffset and y > ymin + yoffset:
            dist = [np.sqrt((x - x0)**2 + (y - y0)**2) for x0, y0 in xyplotted]
            if not dist or min(dist) > dmin:  #,fontweight='bold'
                a = ax.text(x,
                            y,
                            'L',
                            fontsize=20,
                            ha='center',
                            va='center',
                            color='r',
                            fontweight='normal')
                b = ax.text(x,
                            y - yoffset,
                            repr(int(p)),
                            fontsize=12,
                            ha='center',
                            va='top',
                            color='r',
                            fontweight='normal')
                a.set_path_effects([
                    path_effects.Stroke(linewidth=1.5, foreground='black'),
                    path_effects.SimpleLineShadow(),
                    path_effects.Normal()
                ])
                b.set_path_effects([
                    path_effects.Stroke(linewidth=1.5, foreground='black'),
                    path_effects.SimpleLineShadow(),
                    path_effects.Normal()
                ])
                xyplotted.append((x, y))

    #Plot high pressures
    xyplotted = []
    for x, y, p in zip(xhighs, yhighs, highvals):
        if x < xmax - yoffset and x > xmin + yoffset and y < ymax - yoffset and y > ymin + yoffset:
            dist = [np.sqrt((x - x0)**2 + (y - y0)**2) for x0, y0 in xyplotted]
            if not dist or min(dist) > dmin:
                a = ax.text(x,
                            y,
                            'H',
                            fontsize=20,
                            ha='center',
                            va='center',
                            color='b',
                            fontweight='normal')
                b = ax.text(x,
                            y - yoffset,
                            repr(int(p)),
                            fontsize=12,
                            ha='center',
                            va='top',
                            color='b',
                            fontweight='normal')
                a.set_path_effects([
                    path_effects.Stroke(linewidth=1.5, foreground='black'),
                    path_effects.SimpleLineShadow(),
                    path_effects.Normal()
                ])
                b.set_path_effects([
                    path_effects.Stroke(linewidth=1.5, foreground='black'),
                    path_effects.SimpleLineShadow(),
                    path_effects.Normal()
                ])
                xyplotted.append((x, y))
Exemplo n.º 29
0
def animation_plot(animations, savepath, parents, interval=33.33):
    for ai in range(len(animations)):
        anim = animations[ai][0].copy()

        joints = anim[:, :-4].copy()
        root_x = anim[:, -4].copy()
        root_y = anim[:, -3].copy()
        root_z = anim[:, -2].copy()
        root_r = anim[:, -1].copy()
        joints = joints.reshape((len(joints), -1, 3))
        joints[:, :, 0] = joints[:, :, 0] - joints[0:1, 0:1, 0]
        joints[:, :, 2] = joints[:, :, 2] - joints[0:1, 0:1, 2]

        #    fid_l, fid_r = np.array([4,5]), np.array([9,10])
        #    foot_heights = np.minimum(joints[:,fid_l,1], joints[:,fid_r,1]).min(axis=1)
        #    floor_height = softmin(foot_heights, softness=0.5, axis=0)
        #    joints[:,:,1] -= floor_height

        rotation = Quaternions.id(1)
        offsets = []
        translation = np.array([[0, 0, 0]])

        for i in range(len(joints)):
            joints[i, :, :] = rotation * joints[i]
            joints[i, :, 0] = joints[i, :, 0] + translation[0, 0]
            joints[i, :, 1] = joints[i, :, 1] + translation[0, 1]
            joints[i, :, 2] = joints[i, :, 2] + translation[0, 2]
            rotation = Quaternions.from_angle_axis(
                -root_r[i], np.array([0, 1, 0])) * rotation
            offsets.append(rotation * np.array([0, 0, 1]))
            translation = translation + rotation * np.array(
                [root_x[i], root_y[i], root_z[i]])

        animations[ai] = joints
    scale = 8.25 * ((len(animations)) / 2.)

    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(111, projection="3d")
    ax.set_xlim3d(-scale * 30, scale * 30)
    ax.set_zlim3d(0, scale * 60)
    ax.set_ylim3d(-scale * 30, scale * 30)
    ax.set_xticks([], [])
    ax.set_yticks([], [])
    ax.set_zticks([], [])
    ax.view_init(0, 90)
    ax.set_aspect("equal")

    plt.tight_layout()

    acolors = ["green", "red"]  #list(sorted(colors.cnames.keys()))[::-1]
    lines = []

    for ai, anim in enumerate(animations):
        lines.append([
            plt.plot([0, 0], [0, 0], [0, 0],
                     color=acolors[ai],
                     lw=2,
                     path_effects=[
                         pe.Stroke(linewidth=3, foreground="black"),
                         pe.Normal()
                     ])[0] for _ in range(anim.shape[1])
        ])

    def animate(i):
        changed = []
        for ai in range(len(animations)):
            offset = 200 * (ai - ((len(animations)) / 2))
            for j in range(len(parents)):
                if parents[j] != -1:
                    lines[ai][j].set_data([
                        animations[ai][i, j, 0] + offset,
                        animations[ai][i, parents[j], 0] + offset
                    ], [
                        -animations[ai][i, j, 2],
                        -animations[ai][i, parents[j], 2]
                    ])
                    lines[ai][j].set_3d_properties([
                        animations[ai][i, j, 1], animations[ai][i, parents[j],
                                                                1]
                    ])
            changed += lines

        return changed

    ani = animation.FuncAnimation(fig,
                                  animate,
                                  np.arange(len(animations[0])),
                                  interval=interval)
    ani.save(savepath, writer="ffmpeg", fps=30)
    plt.close()
ax.scatter(Px, Py, edgecolor="black", facecolor="white", zorder=20)
ax.scatter(Px, Py, edgecolor="None", facecolor="C1", alpha=0.5, zorder=30)

y, dy = 1.0, 0.125
style = "arc,angleA=-0,angleB=0,armA=-100,armB=0,rad=0"

for i in range(len(I)):
    text = ax.annotate(
        "Point " + chr(ord("A") + i),
        xy=(Px[i], Py[i]),
        xycoords="data",
        xytext=(0, 18),
        textcoords="offset points",
        ha="center",
        size="small",
        arrowprops=dict(
            arrowstyle="->", shrinkA=0, shrinkB=5, color="black", linewidth=0.75
        ),
    )
    text.set_path_effects(
        [path_effects.Stroke(linewidth=2, foreground="white"), path_effects.Normal()]
    )
    text.arrow_patch.set_path_effects(
        [path_effects.Stroke(linewidth=2, foreground="white"), path_effects.Normal()]
    )

plt.tight_layout()
plt.savefig("../../figures/ornaments/annotation-direct.pdf")
plt.show()