Exemplo n.º 1
0
import proplot as plot
import numpy as np
state = np.random.RandomState(51423)
fig, axs = plot.subplots(nrows=2, axwidth=3.2, share=0)
axs.format(xformatter='null',
           yformatter='null',
           abc=True,
           abcloc='ul',
           abcstyle='A.',
           suptitle='Getting individual colors from colormaps and cycles')

# Drawing from colormap
ax = axs[0]
name = 'Deep'
cmap = plot.Colormap(name)
idxs = plot.arange(0, 1, 0.2)
state.shuffle(idxs)
for idx in idxs:
    data = (state.rand(20) - 0.4).cumsum()
    h = ax.plot(data,
                lw=5,
                color=(name, idx),
                label=f'idx {idx:.1f}',
                legend='r',
                legend_kw={'ncols': 1})
ax.colorbar(cmap, loc='ur', label='colormap', length='12em')
ax.format(title='Drawing from the Solar colormap', grid=True)

# Drawing from color cycle
ax = axs[1]
idxs = np.arange(6)
Exemplo n.º 2
0
def plot_weights_heatmap(wrf, s5p, regridder, wrf_file, output_fig_dir):
    '''Plot the heatmap of weights for one pixel'''

    # get the value of one pixel around the simulation center
    vcd = s5p['nitrogendioxide_tropospheric_column']

    # assign coords
    vcd = vcd.assign_coords(y=np.arange(vcd.shape[0]),
                            x=np.arange(vcd.shape[1]))

    sel_pixel = vcd.where((vcd.longitude > wrf.coords['lon'].mean() - 0.1) &
                          (vcd.longitude < wrf.coords['lon'].mean() + 0.1) &
                          (vcd.latitude > wrf.coords['lat'].mean() - 0.1) &
                          (vcd.latitude < wrf.coords['lat'].mean() + 0.1),
                          drop=True)[-1:, -1:]

    # calculate the index for raveled s5p data
    #   because the weight is based on raveled arrays
    pixel_y = sel_pixel.coords['y'] - vcd.coords['y'][0]
    pixel_x = sel_pixel.coords['x'] - vcd.coords['x'][0]
    pixel_indice = pixel_y * len(vcd.coords['x']) + pixel_x

    # get the indices
    match_indice = np.where(np.isin(regridder.weights.row, pixel_indice))
    chem_indice = regridder.weights.col[match_indice]

    # get the x/y in chem grids
    chem_y, chem_x = np.unravel_index(
        chem_indice, (wrf['no2'].shape[1], wrf['no2'].shape[2]))

    df = pd.DataFrame(index=np.unique(chem_y), columns=np.unique(chem_x))
    df = df.fillna(0)

    # fill the df with weights
    for df_index in np.arange(len(chem_y)):
        df.loc[chem_y[df_index], chem_x[df_index]] = \
                regridder.weights.data[match_indice][df_index]

    # proplot version
    f, ax = plot.subplots()
    ax.heatmap(
        df.columns,
        df.index,
        df * 100,
        cmap='Blues',
        vmin=0,
        vmax=2,
        N=100,
        lw=0.5,
        edgecolor=None,
        labels=True,
        clip_on=False,
        colorbar='b',
        colorbar_kw={
            'values': plot.arange(0, 2, 0.5),
            'ticks': 0.5,
            'label': 'Weights (%)'
        },
        labels_kw={'fontsize': 5},
        # labels_kw={'weight': 'bold'},
    )
    ax.format(
        alpha=0,
        linewidth=0,
        xticks=[],
        yticks=[],
        # yreverse=True,
        # xloc='top',
        # yloc='right',
        # ticklabelweight='bold',
        # ytickmajorpad=4,
    )

    # convert lon_b/lat_b of the pixel to x/y in chem grid
    nc_ds = Dataset(wrf_file)
    pixel_lon_b = s5p['assembled_lon_bounds'][
        pixel_y.values[0]:pixel_y.values[0] + 2,
        pixel_x.values[0]:pixel_x.values[0] + 2]
    pixel_lat_b = s5p['assembled_lat_bounds'][
        pixel_y.values[0]:pixel_y.values[0] + 2,
        pixel_x.values[0]:pixel_x.values[0] + 2]
    x_y = ll_to_xy(nc_ds, pixel_lat_b, pixel_lon_b, as_int=False).values
    # pair together
    x_y = np.stack((x_y[0], x_y[1]), axis=-1)
    x_y[[-2, -1]] = x_y[[-1, -2]]

    # seaborn version
    '''
    sns.set()
    f, ax = plt.subplots(figsize=(10, 8))
    sns.heatmap(df*100,
                ax=ax,
                cmap="Blues",
                # annot_kws={"size": 15},
                # cbar_kws={'label': 'weights (%)'},
                annot=True, cbar=False,
                xticklabels=False,
                yticklabels=False)
    # add % text
    for t in ax.texts:
        t.set_text(t.get_text() + " %")
    # bug of matplotlib_3.1.1:
    # https://stackoverflow.com/questions/56942670/
    #           matplotlib-seaborn-first-and-last-row-cut-in-half-of-heatmap-plot
    if matplotlib.__version__ == '3.1.1':
        bottom, top = ax.get_ylim()
        ax.set_ylim(bottom + 0.5, top - 0.5)
    pair together
      we need to convert x/y (chem) to x/y relative to axis,
      because the label is at the center, we need to modify values by 0.5
    x_y = np.stack((x_y[0]-chem_x.min()+0.5, x_y[1]-chem_y.min()+0.5), axis=-1)
    x_y[[-2, -1]] = x_y[[-1, -2]]
    '''

    # add polygon
    poly = Polygon(
        x_y,
        edgecolor='orange7',
        # linewidth=2,
        fill=None)
    ax.add_patch(poly)

    # save figure
    output_name = os.path.join(output_fig_dir, 'weights_heatmap.png')
    logging.info(f'Saving weights_heatmap to {output_name}')
    f.savefig(output_name)
Exemplo n.º 3
0
# %%
import proplot as plot
import numpy as np
state = np.random.RandomState(51423)
data = (state.rand(40, 40) - 0.5).cumsum(axis=0).cumsum(axis=1)

# Generate figure
fig, axs = plot.subplots(ncols=2, nrows=2, axwidth=1.7, span=False)
axs.format(
    xlabel='x axis',
    ylabel='y axis',
    suptitle='Modifying diverging colormaps',
)

# Cutting out central colors
levels = plot.arange(-10, 10, 2)
for i, (ax, cut) in enumerate(zip(axs, (None, None, 0.2, -0.1))):
    levels = plot.arange(-10, 10, 2)
    if i == 1 or i == 3:
        levels = plot.edges(levels)
    if i == 0:
        title = 'Even number of levels'
    elif i == 1:
        title = 'Odd number of levels'
    else:
        title = 'Sharper cutoff' if cut > 0 else 'Expanded center'
        title = f'{title}\ncut = ${cut}$'
    ax.format(title=title)
    m = ax.contourf(
        data,
        cmap='Div',
Exemplo n.º 4
0
             colorbar_kw={
                 'length': '8em',
                 'label': 'line colorbar'
             })
ax.colorbar(hs,
            loc='t',
            values=np.arange(0, 10),
            label='line colorbar',
            ticks=2)

# Colorbars from a mappable
ax = fig.subplot(122)
m = ax.contourf(data.T,
                extend='both',
                cmap='algae',
                levels=pplt.arange(0, 3, 0.5))
fig.colorbar(
    m,
    loc='r',
    length=1,  # length is relative
    label='interior ticks',
    tickloc='left')
ax.colorbar(
    m,
    loc='ul',
    length=6,  # length is em widths
    label='inset colorbar',
    tickminor=True,
    alpha=0.5,
)
fig.format(suptitle='Colorbar formatting demo',
Exemplo n.º 5
0
    cmap = 'grays'
    if coord is None:
        title, cmap_kw = 'Original', {}
    elif coord < 0.5:
        title, cmap_kw = f'left={coord}', {'left': coord}
    else:
        title, cmap_kw = f'right={coord}', {'right': coord}
    ax.pcolormesh(data,
                  cmap=cmap,
                  cmap_kw=cmap_kw,
                  colorbar='b',
                  colorbar_kw={'locator': 'null'})
    ax.format(xlabel='x axis', ylabel='y axis', title=title)

# Cutting central colors
levels = plot.arange(-10, 10, 2)
for i, (ax, cut) in enumerate(zip(axs[3:], (None, None, 0.1, 0.2))):
    if i == 0:
        title = 'With central level'
        levels = plot.edges(plot.arange(-10, 10, 2))
    else:
        title = 'Without central level'
        levels = plot.arange(-10, 10, 2)
    if cut is not None:
        title = f'cut = {cut}'
    m = ax.contourf(
        data,
        cmap='Div',
        cmap_kw={'cut': cut},
        extend='both',
        levels=levels,
Exemplo n.º 6
0
# %%
import proplot as plot

fig, axs = plot.subplots(axwidth=1.5, nrows=2, ncols=2, share=0)

# Demonstration that complex arrangements of panels
# do not mess up tight layout algorithm
for ax, side in zip(axs, 'tlbr'):
    ax.panel(side, width='3em')
axs.format(
    xlim=(0, 1),
    ylim=(0, 1),
    xlabel='xlabel',
    ylabel='ylabel',
    yticks=plot.arange(0.2, 0.8, 0.2),
    xticks=plot.arange(0.2, 0.8, 0.2),
    title='Title',
    suptitle='Complex arrangement of panels',
    collabels=['Column 1', 'Column 2'],
    abc=True,
    abcloc='ul',
    titleloc='uc',
    abovetop=False,
)

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_insets:
#
# Inset axes
# ----------
Exemplo n.º 7
0
    basemap={
        (1, 3, 5, 7, 9): False,  # use cartopy in column 1
        (2, 4, 6, 8, 10): True,  # use basemap in column 2
    },
    proj={
        (1, 2): 'mill',  # different projection each row
        (3, 4): 'cyl',
        (5, 6): 'moll',
        (7, 8): 'sinu',
        (9, 10): 'npstere'
    },
    ncols=2,
    nrows=5)
axs.format(suptitle='Figure with several projections')
axs.format(coast=True, latlines=30, lonlines=60)
axs[:, 1].format(labels=True, lonlines=plot.arange(-180, 179, 60))
axs[-1, -1].format(labels=True, lonlines=30)
axs.format(collabels=['Cartopy projections', 'Basemap projections'])
plot.rc.reset()

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_geoplot:
#
# Plotting geographic data
# ------------------------
#
# The below example demonstrates how to plot geographic data with ProPlot.
# It is mostly the same as cartopy, but with some new features powered by the
# `~proplot.wrappers.standardize_2d`, `~proplot.wrappers.default_transform`,
# and `~proplot.wrappers.default_latlon` wrappers.
#
Exemplo n.º 8
0
    title='Main',
    ltitle='Left',
    rtitle='Right',  # different titles
    ultitle='Title 1',
    urtitle='Title 2',
    lltitle='Title 3',
    lrtitle='Title 4',
    toplabels=('Column 1', 'Column 2'),
    leftlabels=('Row 1', 'Row 2'),
    xlabel='xaxis',
    ylabel='yaxis',
    xscale='log',
    xlim=(1, 10),
    xticks=1,
    ylim=(-3, 3),
    yticks=pplt.arange(-3, 3),
    yticklabels=('a', 'bb', 'c', 'dd', 'e', 'ff', 'g'),
    ytickloc='both',
    yticklabelloc='both',
    xtickdir='inout',
    xtickminor=False,
    ygridminor=True,
)

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_rc:
#
# Settings and styles
# -------------------
#
# A dictionary-like object named `~proplot.config.rc` is created when you import
Exemplo n.º 9
0
    linewidth=1,
    titlepad='1em',
    ticklabelsize=9,
    rlines=0.5,
    rlim=(0, 19),
)
for i in range(5):
    xi = x + i * 2 * np.pi / 5
    axs.plot(xi, y[:, i], cycle='FlatUI', zorder=0, lw=3)

# Standard polar plot
axs[0].format(
    title='Normal plot',
    thetaformatter='tau',
    rlabelpos=225,
    rlines=plot.arange(5, 30, 5),
    color='red8',
    tickpad='1em',
)

# Sector plot
axs[1].format(
    title='Sector plot',
    thetadir=-1,
    thetalines=90,
    thetalim=(0, 270),
    theta0='N',
    rlim=(0, 22),
    rlines=plot.arange(5, 30, 5),
)
Exemplo n.º 10
0
ani = animate(nkeff, vmin=0, vmax=11)

ani.save(path + 'nkeffxz.gif', writer='imagemagick', fps=12)

#%% time-mean
import matplotlib.pyplot as plt
import proplot as pplt

pplt.rc.update({'figure.facecolor': 'white'})
pplt.rc['axesfacecolor'] = 'white'

array = [[1, 1, 2]]

fig, ax = pplt.subplots(array, figsize=(7, 4), sharex=0)

ax.format(abc=True, abcloc='l', abcstyle='(a)')

m1 = ax[0].contourf(kmean,
                    cmap=plt.cm.jet,
                    levels=pplt.arange(1, 6, 0.05),
                    add_colorbar=False)
ax[0].colorbar(m1, loc='bottom', width=0.1)
ax[0].format(title='time mean $K_{WD}$',
             xlabel='x-distance (m)',
             ylabel='depth (m)')

kprof.plot(ax=ax[1], y='Z')
ax[1].format(title='x-mean of $K_{WD}$',
             xlabel='$K_{WD}$ ($m^2$ $s^{-1}$)',
             ylabel='depth (m)')
Exemplo n.º 11
0
import numpy as np

# Sample data
M, N = 300, 3
state = np.random.RandomState(51423)
x = state.normal(
    size=(M, N)) + state.rand(M)[:, None] * np.arange(N) + 2 * np.arange(N)

# Sample overlayed histograms
fig, ax = pplt.subplots(refwidth=4, refaspect=(3, 2))
ax.format(suptitle='Overlaid histograms',
          xlabel='distribution',
          ylabel='count')
res = ax.hist(
    x,
    pplt.arange(-3, 8, 0.2),
    filled=True,
    alpha=0.7,
    edgecolor='k',
    cycle=('indigo9', 'gray3', 'red9'),
    labels=list('abc'),
    legend='ul',
)

# %%
import proplot as pplt
import numpy as np

# Sample data
N = 500
state = np.random.RandomState(51423)
Exemplo n.º 12
0
dset = xr.open_dataset('CDR_amazonbasin.nc')
# masking undefined values outside the basin area
dset['precip'] = dset['precip'].where(dset['precip'] != -99.)
# seasonal cycle
season = dset['precip'].groupby('datetime.season').mean('datetime')

basin = 'amazon_shape.shp' # shapefile
proj  =  ccrs.PlateCarree() # cartopy projection

f, ax = plot.subplots(axwidth=3.5, nrows=2, ncols=2, tight=True, proj='pcarree',
                      proj_kw={'lon_0':180},)

ax.format(land=False, coast=True, innerborders=True, borders=True, grid=False,
          geogridlinewidth=0, labels=True,
          latlim=(-21, 12), lonlim=(275, 315),
          latlines=plot.arange(-20, 10, 5), lonlines=plot.arange(-95, -20, 5),
          large='15px')

map1 = ax[0,0].contourf(dset['lon'], dset['lat'], season[0,:,:],
                     cmap='BuPu', levels=np.arange(50, 500, 50), extend='both')
map2 = ax[0,1].contourf(dset['lon'], dset['lat'], season[2,:,:],
                     cmap='BuPu', levels=np.arange(50, 500, 50), extend='both')
map3 = ax[1,0].contourf(dset['lon'], dset['lat'], season[1,:,:],
                     cmap='BuPu', levels=np.arange(50, 500, 50), extend='both')
map4 = ax[1,1].contourf(dset['lon'], dset['lat'], season[3,:,:],
                     cmap='BuPu', levels=np.arange(50, 500, 50), extend='both')

ax[1,0].colorbar(map3, loc='b', label='mm/month', shrink=0.1)
ax[1,1].colorbar(map4, loc='b', label='mm/month', shrink=0.1)

ax[0,0].format(title='DJF')
Exemplo n.º 13
0
# `~proplot.colors.ColorDatabase` class. This is useful if you spot a
# nice color in one of the available colormaps or color cycles and want
# to use it for some arbitrary plot element. Use the `~proplot.utils.to_rgb` or
# `~proplot.utils.to_rgba` functions to retrieve the RGB or RGBA channel values.

# %%
import proplot as pplt
import numpy as np

# Initial figure and random state
state = np.random.RandomState(51423)
fig = pplt.figure(refwidth=2.2, share=False)

# Drawing from colormaps
name = 'Deep'
idxs = pplt.arange(0, 1, 0.2)
state.shuffle(idxs)
ax = fig.subplot(121, grid=True, title=f'Drawing from colormap {name!r}')
for idx in idxs:
    data = (state.rand(20) - 0.4).cumsum()
    h = ax.plot(data,
                lw=5,
                color=(name, idx),
                label=f'idx {idx:.1f}',
                legend='l',
                legend_kw={'ncols': 1})
ax.colorbar(pplt.Colormap(name), loc='l', locator='none')

# Drawing from color cycles
name = 'Qual1'
idxs = np.arange(6)
Exemplo n.º 14
0
    large=12,
    facecolor='gray8',
    figurefacecolor='gray8',
    suptitlecolor='w',
    gridcolor='w',
    color='w',
    titleloc='upper center',
    titlecolor='w',
    titleborder=False,
)
fig, axs = plot.subplots(nrows=6, axwidth=5, aspect=(8, 1), share=0)

# Fraction formatters
axs[0].format(
    xlim=(0, 3 * np.pi),
    xlocator=plot.arange(0, 4, 0.25) * np.pi,
    xformatter='pi',
    title='FracFormatter',
)
axs[1].format(
    xlim=(0, 2 * np.e),
    xlocator=plot.arange(0, 2, 0.5) * np.e,
    xticklabels='e',
    title='FracFormatter',
)

# Geographic formatter
axs[2].format(xlim=(-90, 90),
              xlocator=plot.arange(-90, 90, 30),
              xformatter='deglat',
              title='Geographic preset')
Exemplo n.º 15
0
state = np.random.RandomState(51423)
x = np.linspace(0, 2 * np.pi, N)
y = 100 * (state.rand(N, 5) - 0.3).cumsum(axis=0) / N
fig, axs = plot.subplots([[1, 1, 2, 2], [0, 3, 3, 0]], proj='polar')
axs.format(
    suptitle='Polar axes demo', linewidth=1, titlepad='1em',
    ticklabelsize=9, rlines=0.5, rlim=(0, 19),
)
for i in range(5):
    xi = x + i * 2 * np.pi / 5
    axs.plot(xi, y[:, i], cycle='FlatUI', zorder=0, lw=3)

# Standard polar plot
axs[0].format(
    title='Normal plot', thetaformatter='tau',
    rlabelpos=225, rlines=plot.arange(5, 30, 5),
    color='red8', tickpad='1em',
)

# Sector plot
axs[1].format(
    title='Sector plot', thetadir=-1, thetalines=90, thetalim=(0, 270), theta0='N',
    rlim=(0, 22), rlines=plot.arange(5, 30, 5),
)

# Annular plot
axs[2].format(
    title='Annular plot', thetadir=-1, thetalines=20, gridcolor='red',
    r0=-20, rlim=(0, 22), rformatter='null', rlocator=2
)
Exemplo n.º 16
0
state = np.random.RandomState(51423)
data = (state.normal(0, 1, size=(33, 33))).cumsum(axis=0).cumsum(axis=1)
axs.format(suptitle='Pcolor plot with levels')
for ax, n, mode, side in zip(axs, (200, 10), ('Ambiguous', 'Discernible'), 'lr'):
    ax.pcolor(data, cmap='spectral_r', N=n, symmetric=True, colorbar=side)
    ax.format(title=f'{mode} level boundaries', yformatter='null')

# %%
import proplot as plot
import numpy as np
fig, axs = plot.subplots(
    [[0, 0, 1, 1, 0, 0], [2, 3, 3, 4, 4, 5]],
    wratios=(1.5, 0.5, 1, 1, 0.5, 1.5), axwidth=1.7, ref=1, right='2em'
)
axs.format(suptitle='DiscreteNorm color-range standardization')
levels = plot.arange(0, 360, 45)
state = np.random.RandomState(51423)
data = (20 * (state.rand(20, 20) - 0.4).cumsum(axis=0).cumsum(axis=1)) % 360

# Cyclic colorbar with distinct end colors
ax = axs[0]
ax.pcolormesh(
    data, levels=levels, cmap='phase', extend='neither',
    colorbar='b', colorbar_kw={'locator': 90}
)
ax.format(title='cyclic colormap\nwith distinct end colors')

# Colorbars with different extend values
for ax, extend in zip(axs[1:], ('min', 'max', 'neither', 'both')):
    ax.pcolormesh(
        data[:, :10], levels=levels, cmap='oxy',
Exemplo n.º 17
0
def plot_distribution(emc_dict, wrf_dict, wrf, stations):
    '''Plot the distribution'''
    # set the figure
    cmap = 'Spectral'
    f, axs = plot.subplots(
        ncols=2,
        nrows=int(len(wrf_dict.keys()) / 2),
        tight=True,
        proj='pcarree',
    )
    axs.format(abc=True, abcloc='ul', abcstyle='(a)')

    # plot the map
    axs.add_feature(provinces, edgecolor='k', linewidth=.3)

    # iterate through vars (no2, o3 ...)
    for index, key in enumerate(wrf_dict.keys()):
        # get x/y data
        y_wrf = wrf_dict[key]
        y_emc = emc_dict[key].iloc[:, 2:-2].T
        x = y_wrf.coords['Time']

        # get the correct var names
        insert_sub = re.search(r"\d", key)
        if insert_sub:
            letter = key.upper()[:insert_sub.start(0)]
            num = f'$_{key[insert_sub.start(0)]}$'
        else:
            letter = key.upper()
            num = ''

        # get specific var
        varname = list(emc_dict.keys())[index]
        tmp_df = emc_dict[varname]
        stations_lon = tmp_df['longitude']
        stations_lat = tmp_df['latitude']
        col = tmp_df.columns[2]

        # plot wrf simulation
        m = axs[index].pcolormesh(
            wrf.dv['lon'],
            wrf.dv['lat'],
            wrf.dv[varname].isel(bottom_top=0) * 1e3,  # ppbv
            cmap=cmap,
            vmin=0,
            vmax=vmax[varname],
            levels=256)

        # plot station observation
        sca = axs[index].scatter(
            tmp_df['longitude'],
            tmp_df['latitude'],
            c=tmp_df[col],
            cmap=cmap,
            color=256,
            vmin=0,
            vmax=vmax[varname],
            linewidths=1,
            edgecolors='k',
        )

        # set colorbar
        cb_levels = plot.arange(0, vmax[varname], vspace[varname])
        axs[index].colorbar(m, loc='r', values=cb_levels, label='(ppbv)')
        axs[index].format(title=f'{letter}{num}')

    # get time in string format
    suptitle = pd.to_datetime(wrf_dict[key].coords['Time'].values) \
        .strftime('%Y%m%d %H:%M:%S (UTC)')

    # set axis again
    axs.format(
        lonlim=(wrf.dv['lon'].min(), wrf.dv['lon'].max()),
        latlim=(wrf.dv['lat'].min(), wrf.dv['lat'].max()),
        labels=True,
        lonlines=1,
        latlines=1,
        suptitle=suptitle,
    )

    return f
Exemplo n.º 18
0
# Custom defaults of each type
pplt.rc['cmap.sequential'] = 'PuBuGn'
pplt.rc['cmap.diverging'] = 'PiYG'
pplt.rc['cmap.cyclic'] = 'bamO'
pplt.rc['cmap.qualitative'] = 'flatui'

# Make plots. Note the default behavior is sequential=True or diverging=True
# depending on whether data contains negative values (see below).
fig = pplt.figure(refwidth=2.2, span=False, suptitle='Colormap types')
axs = fig.subplots(ncols=2, nrows=2)
axs.format(xformatter='none', yformatter='none')
axs[0].pcolor(data, sequential=True, colorbar='l', extend='max')
axs[1].pcolor(data - 5, diverging=True, colorbar='r', extend='both')
axs[2].pcolor(data % 8, cyclic=True, colorbar='l')
axs[3].pcolor(data,
              levels=pplt.arange(0, 12, 2),
              qualitative=True,
              colorbar='r')
types = ('sequential', 'diverging', 'cyclic', 'qualitative')
for ax, typ in zip(axs, types):
    ax.format(title=typ.title() + ' colormap')
pplt.rc.reset()

# %%
import proplot as pplt
import numpy as np

# Sample data
N = 20
state = np.random.RandomState(51423)
data = np.cumsum(state.rand(N, N), axis=1) - 6
Exemplo n.º 19
0
# Create figure
fig, axs = pplt.subplots(ncols=2, nrows=2, refwidth=1.7, span=False)
axs.format(
    xlabel='x axis', ylabel='y axis', xticklabels='none',
    suptitle='Modifying diverging colormaps',
)

# Cutting out central colors
titles = (
    'Negative-positive cutoff', 'Neutral-valued center',
    'Sharper cutoff', 'Expanded center'
)
for i, (ax, title, cut) in enumerate(zip(axs, titles, (None, None, 0.2, -0.1))):
    if i % 2 == 0:
        kw = {'levels': pplt.arange(-10, 10, 2)}  # negative-positive cutoff
    else:
        kw = {'values': pplt.arange(-10, 10, 2)}  # dedicated center
    if cut is not None:
        fmt = pplt.SimpleFormatter()  # a proper minus sign
        title = f'{title}\ncut = {fmt(cut)}'
    ax.format(title=title)
    m = ax.contourf(
        data, cmap='Div', cmap_kw={'cut': cut}, extend='both',
        colorbar='b', colorbar_kw={'locator': 'null'},
        **kw  # level edges or centers
    )

# %%
import proplot as pplt
import numpy as np
Exemplo n.º 20
0
hs = ax.plot(data,
             lw=4,
             cycle=cycle,
             colorbar='lr',
             colorbar_kw={
                 'length': '8em',
                 'label': 'from lines'
             })
axs.colorbar(hs, loc='t', values=np.arange(0, 10), label='from lines', ticks=2)

# Colorbars from a mappable
ax = axs[1]
m = ax.contourf(data.T,
                extend='both',
                cmap='algae',
                levels=plot.arange(0, 3, 0.5))
fig.colorbar(m, length=1, loc='r', label='inside ticks', tickloc='left')
ax.colorbar(m,
            loc='ul',
            length=1,
            tickminor=True,
            label='inset colorbar',
            alpha=0.5)
axs.format(suptitle='Colorbar formatting demo',
           xlabel='xlabel',
           ylabel='ylabel',
           abovetop=False)

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_legends:
#
Exemplo n.º 21
0
    abcstyle='A.',
    title='Main',
    ltitle='Left',
    rtitle='Right',  # different titles
    urtitle='Title A',
    lltitle='Title B',
    lrtitle='Title C',  # extra titles
    toplabels=('Column 1', 'Column 2'),
    leftlabels=('Row 1', 'Row 2'),
    xlabel='x-axis',
    ylabel='y-axis',
    xscale='log',
    xlim=(1, 10),
    xticks=1,
    ylim=(-3, 3),
    yticks=plot.arange(-3, 3),
    yticklabels=('a', 'bb', 'c', 'dd', 'e', 'ff', 'g'),
    ytickloc='both',
    yticklabelloc='both',
    xtickdir='inout',
    xtickminor=False,
    ygridminor=True,
)

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_container:
#
# Subplot containers
# ------------------
#
# Instead of an `~numpy.ndarray` of subplots, `~proplot.ui.subplots` returns a
Exemplo n.º 22
0
    abcstyle='A.',
    title='Main',
    ltitle='Left',
    rtitle='Right',  # different titles
    urtitle='Title A',
    lltitle='Title B',
    lrtitle='Title C',  # extra titles
    collabels=['Column label 1', 'Column label 2'],
    rowlabels=['Row label 1', 'Row label 2'],
    xlabel='x-axis',
    ylabel='y-axis',
    xscale='log',
    xlim=(1, 10),
    xticks=1,
    ylim=(-2, 2),
    yticks=plot.arange(-2, 2),
    yticklabels=('a', 'bb', 'c', 'dd', 'e'),
    ytickloc='both',
    yticklabelloc='both',
    xtickdir='inout',
    xtickminor=False,
    ygridminor=True,
    linewidth=0.8,
    gridlinewidth=0.8,
    gridminorlinewidth=0.5,
)

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_rc:
#
# Changing rc settings