Esempio n. 1
0
# commands `~matplotlib.axes.Axes.plot`, `~matplotlib.axes.Axes.scatter`,
# `~matplotlib.axes.Axes.pcolormesh`, and `~matplotlib.axes.Axes.contourf`.
# See the :ref:`1d plotting <ug_1dplots>` and :ref:`2d plotting <ug_2dplots>`
# sections for details on the features added by ProPlot.

# %%
import proplot as plot
import numpy as np

# Sample data
N = 20
state = np.random.RandomState(51423)
data = (state.rand(N, N) - 0.5).cumsum(axis=0).cumsum(axis=1)

# Example plots
cycle = plot.Cycle('greys', left=0.2, N=5)
fig, axs = plot.subplots(ncols=2, nrows=2, share=0, width=5)
axs[0].plot(data[:, :5], linewidth=2, linestyle='--', cycle=cycle)
axs[1].scatter(data[:, :5], marker='x', cycle=cycle)
axs[2].pcolormesh(data, cmap='greys')
axs[3].contourf(data, cmap='greys')
axs.format(abc=True,
           xlabel='xlabel',
           ylabel='ylabel',
           suptitle='Quick plotting demo')

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_format:
#
# Formatting stuff
# ----------------
Esempio n. 2
0
import proplot as plot
import numpy as np
fig, axs = plot.subplots(ncols=2, share=0, axwidth=2.3)
state = np.random.RandomState(51423)
data = (20 * state.rand(10, 21) - 10).cumsum(axis=0)

# Cycle from on-the-fly monochromatic colormap
ax = axs[0]
lines = ax.plot(data[:, :5], cycle='plum', cycle_kw={'fade': 85}, lw=5)
fig.colorbar(lines, loc='b', col=1, values=np.arange(0, len(lines)))
fig.legend(lines, loc='b', col=1, labels=np.arange(0, len(lines)))
ax.format(title='Cycle from color')

# Cycle from registered colormaps
ax = axs[1]
cycle = plot.Cycle('blues', 'reds', 'oranges', 15, left=0.1)
lines = ax.plot(data[:, :15], cycle=cycle, lw=5)
fig.colorbar(lines, loc='b', col=2, values=np.arange(0, len(lines)), locator=2)
fig.legend(lines, loc='b', col=2, labels=np.arange(0, len(lines)), ncols=4)
ax.format(title='Cycle from merged colormaps',
          suptitle='Color cycles from colormaps')

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_cycles_other:
#
# Cycles of other properties
# --------------------------
#
# `~proplot.constructor.Cycle` can also generate cyclers that change
# properties other than color. Below, a single-color dash style cycler is
# constructed and applied to the axes locally. To apply it globally, simply
Esempio n. 3
0
#
# The `~proplot.wrappers.standardize_1d` wrapper is used to standardize
# positional arguments across all 1D plotting methods.
# `~proplot.wrappers.standardize_1d` allows you to optionally omit *x*
# coordinates, in which case they are inferred from the data. It also permits
# passing 2D *y* coordinate arrays to any plotting method, in which case the
# plotting method is called for each column of the array.

# %%
import proplot as plot
import numpy as np

# Figure and sample data
N = 5
state = np.random.RandomState(51423)
with plot.rc.context({'axes.prop_cycle': plot.Cycle('Grays', N=N, left=0.3)}):
    fig, axs = plot.subplots(ncols=2, share=False)
    x = np.linspace(-5, 5, N)
    y = state.rand(N, 5)
    axs.format(xlabel='xlabel', ylabel='ylabel', ymargin=0.05)
    axs.format(suptitle='Standardized arguments demonstration')

    # Plot by passing both x and y coordinates
    ax = axs[0]
    ax.area(x, -1 * y / N, stacked=True)
    ax.bar(x, y, linewidth=0, alpha=1, width=0.8 * (x[1] - x[0]))
    ax.plot(x, y + 1, linewidth=2)
    ax.scatter(x, y + 2, marker='s', markersize=5**2)
    ax.format(title='Manual x coordinates')

    # Plot by passing just y coordinates
Esempio n. 4
0
# through `~proplot.constructor.Locator` and `~proplot.constructor.Formatter`.
# The colorbar width and length can be changed with the `width` and `length`
# keyword args. Colorbar widths are now specified in *physical units*,
# which helps avoid colorbars that look "too skinny" or "too fat" and
# preserves the look of the figure when the figure size changes.

# %%
import proplot as plot
import numpy as np
fig, axs = plot.subplots(share=0, ncols=2, axwidth=2)

# Colorbars from lines
ax = axs[0]
state = np.random.RandomState(51423)
data = 1 + (state.rand(12, 10) - 0.45).cumsum(axis=0)
cycle = plot.Cycle('algae')
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',
Esempio n. 5
0
def plot_lines(emc_dict, wrf_dict, wrf, stations, type='mean', loc=True):
    '''
    Plot the lines
    '''
    if loc:
        ax_array = [[1, 1, 2, 3], [1, 1, 4, 5]]
        hratios = (1, 1)
        wratios = (1, 1, 2, 2)
        proj = {1: 'pcarree'}
    else:
        ax_array = [[1, 2], [3, 4]]
        proj = None
        hratios = None
        wratios = None

    # set the figure
    f, axs = plot.subplots(
        ax_array,
        share=0,
        tight=True,
        axheight=3,
        hratios=hratios,
        wratios=wratios,
        proj=proj,
    )
    axs.format(
        abc=True,
        abcloc='ul',
        abcstyle='(a)',
        grid=False,
        share=3,
    )
    # rotation of the xaxis labels
    if loc:
        axs[1:].format(xrotation=0)
    else:
        axs.format(xrotation=0)

    if loc:
        # plot the map
        axs[0].add_feature(provinces, edgecolor='k', linewidth=.3)
        tmp_df = emc_dict[list(emc_dict.keys())[0]]
        stations_lon = tmp_df['longitude']
        stations_lat = tmp_df['latitude']

        # plot the stelected stations
        if type == 'mean':
            axs[0].scatter(stations_lon,
                           stations_lat,
                           edgecolors='red9',
                           facecolors="None")
        elif type == 'station':
            clist = []
            for cdict in list(plot.Cycle('ggplot')):
                clist.append(cdict['color'])
            axs[0].scatter(stations_lon,
                           stations_lat,
                           c=clist[:len(stations_lon)],
                           cycle=plot.Cycle('ggplot'))

        # crop to the interested region
        axs[0].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,
                      title='')

    # iterate through vars (no2, o3 ...)
    for pic, key in enumerate(wrf_dict.keys()):
        if loc:
            pic += 1

        # get x/y data
        y_wrf = wrf_dict[key]
        y_emc = emc_dict[key].iloc[:, 2:-2].T
        x = y_wrf.coords['Time']

        # get station codes
        codes = stations.set_index('longitude')\
                        .loc[emc_dict[key]['longitude']]\
                        .reset_index(inplace=False)['code'].values

        # plot lines
        if type == 'station':
            y1 = y_emc
            y2 = y_wrf
            label_emc = codes
            label_wrf = ''
            cycle_emc = 'ggplot'
            cycle_wrf = plot.Cycle('ggplot', dashes=[(1, 0.5)])
            color_emc = None
            color_wrf = None
        elif type == 'mean':
            y1 = y_emc.mean(axis=1)
            y2 = y_wrf.mean('dim_0')
            label_emc = 'OBS'
            label_wrf = 'WRF-Chem'
            cycle_emc = None
            cycle_wrf = None
            color_emc = 'red9'
            color_wrf = 'blue9'

        line_emc = axs[pic].plot(x,
                                 y1,
                                 cycle=cycle_emc,
                                 color=color_emc,
                                 labels=label_emc)

        line_wrf = axs[pic].plot(x,
                                 y2,
                                 cycle=cycle_wrf,
                                 color=color_wrf,
                                 labels=label_wrf)

        # set axis format
        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 = ''

        # clean formats and labels
        axs[pic].format(xformatter='%H:%M',
                        xlocator=('hour', range(0, len(x), 2)),
                        xminorlocator=('hour', range(0, len(x), 1)),
                        xlabel='Hour (UTC)',
                        ylabel=f'{letter}{num} (ppbv)')

    # legend
    if type == 'station':
        f.legend(line_emc, loc='r', ncols=1)
    elif type == 'mean':
        f.legend((line_emc, line_wrf), loc='r', ncols=1)

    return f
Esempio n. 6
0
#    By default, when choosing the *x* or *y* axis limits,
#    proplot ignores out-of-bounds data along the other axis if it was explicitly
#    fixed by `~matplotlib.axes.Axes.set_xlim` or `~matplotlib.axes.Axes.set_ylim` (or,
#    equivalently, by passing `xlim` or `ylim` to `proplot.axes.CartesianAxes.format`).
#    This can be useful if you wish to restrict the view along a "dependent" variable
#    axis within a large dataset. To disable this feature, pass ``inbounds=False`` to
#    the plotting command or set :rcraw:`axes.inbounds` to ``False`` (see also
#    the :rcraw:`cmap.inbounds` setting and the :ref:`user guide <ug_2dstd>`).

# %%
import proplot as pplt
import numpy as np

N = 5
state = np.random.RandomState(51423)
with pplt.rc.context({'axes.prop_cycle': pplt.Cycle('Grays', N=N, left=0.3)}):
    # Sample data
    x = np.linspace(-5, 5, N)
    y = state.rand(N, 5)
    fig = pplt.figure(share=False, suptitle='Standardized input demonstration')

    # Plot by passing both x and y coordinates
    ax = fig.subplot(121, title='Manual x coordinates')
    ax.area(x, -1 * y / N, stack=True)
    ax.bar(x, y, linewidth=0, alpha=1, width=0.8)
    ax.plot(x, y + 1, linewidth=2)
    ax.scatter(x, y + 2, marker='s', markersize=5**2)

    # Plot by passing just y coordinates
    # Default x coordinates are inferred from DataFrame,
    # inferred from DataArray, or set to np.arange(0, y.shape[0])
Esempio n. 7
0
# `~proplot.axes.PlotAxes.scatter`, along with the "2D" plotting commands
# `~proplot.axes.PlotAxes.pcolormesh` and `~proplot.axes.PlotAxes.contourf`.
# See the :ref:`1D plotting <ug_1dplots>` and :ref:`2D plotting <ug_2dplots>`
# sections for details on the features added by proplot.

# %%
import proplot as pplt
import numpy as np

# Sample data
N = 20
state = np.random.RandomState(51423)
data = N + (state.rand(N, N) - 0.55).cumsum(axis=0).cumsum(axis=1)

# Example plots
cycle = pplt.Cycle('greys', left=0.2, N=5)
fig, axs = pplt.subplots(ncols=2, nrows=2, figwidth=5, share=False)
axs[0].plot(data[:, :5], linewidth=2, linestyle='--', cycle=cycle)
axs[1].scatter(data[:, :5], marker='x', cycle=cycle)
axs[2].pcolormesh(data, cmap='greys')
m = axs[3].contourf(data, cmap='greys')
axs.format(abc='a.',
           titleloc='l',
           title='Title',
           xlabel='xlabel',
           ylabel='ylabel',
           suptitle='Quick plotting demo')
fig.colorbar(m, loc='b', label='label')

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_format:
Esempio n. 8
0
# than relative units using the `extendsize` keyword rather than matplotlib's
# `extendfrac`. The default `extendsize` values are :rcraw:`colorbar.extend` (for
# outer colorbars) and :rcraw:`colorbar.insetextend` (for inset colorbars).
# See `~proplot.axes.Axes.colorbar` for details.

# %%
import proplot as pplt
import numpy as np

fig = pplt.figure(share=False, refwidth=2)

# Colorbars from lines
ax = fig.subplot(121)
state = np.random.RandomState(51423)
data = 1 + (state.rand(12, 10) - 0.45).cumsum(axis=0)
cycle = pplt.Cycle('algae')
hs = ax.line(data,
             lw=4,
             cycle=cycle,
             colorbar='lr',
             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