Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# ProPlot axis scales can be instantiated without the axis instance (e.g.
# ``plot.LogScale()`` instead of ``plot.LogScale(ax.xaxis)``).
# * The default `subs` for the ``'symlog'`` axis scale is now ``np.arange(1, 10)``,
# and the default `linthresh` is now ``1``. Also the ``'log'`` and ``'symlog'``
# axis scales now accept the keywords `base`, `linthresh`, `linscale`, and
# `subs` rather than keywords with trailing ``x`` or ``y``.
# %%
import proplot as plot
import numpy as np
N = 200
lw = 3
plot.rc.update({
'linewidth': 1, 'ticklabelweight': 'bold', 'axeslabelweight': 'bold'
})
fig, axs = plot.subplots(ncols=2, nrows=2, axwidth=1.8, share=0)
axs.format(suptitle='Axis scales demo', ytickminor=True)
# Linear and log scales
axs[0].format(yscale='linear', ylabel='linear scale')
axs[1].format(ylim=(1e-3, 1e3), yscale='log', ylabel='log scale')
axs[:2].plot(np.linspace(0, 1, N), np.linspace(0, 1000, N), lw=lw)
# Symlog scale
ax = axs[2]
ax.format(yscale='symlog', ylabel='symlog scale')
ax.plot(np.linspace(0, 1, N), np.linspace(-1000, 1000, N), lw=lw)
# Logit scale
ax = axs[3]
ax.format(yscale='logit', ylabel='logit scale')
ax.plot(np.linspace(0, 1, N), np.linspace(0.01, 0.99, N), lw=lw)
# intense colormap colors on one side of the midpoint will be truncated.
# * With unfair scaling, the gradations on either side of the midpoint are warped
# so that the full range of colormap colors is traversed. This configuration should
# be used with care, as it may lead you to misinterpret your data!
#
# The below example demonstrates how these normalizers can be used for datasets
# with unusual statistical distributions.
# %%
import proplot as plot
import numpy as np
# Linear segmented norm
state = np.random.RandomState(51423)
data = 10**(2 * state.rand(20, 20).cumsum(axis=0) / 7)
fig, axs = plot.subplots(ncols=2, axwidth=2.4)
ticks = [5, 10, 20, 50, 100, 200, 500, 1000]
for i, (norm, title) in enumerate(zip(
('linear', 'segmented'),
('Linear normalizer', 'LinearSegmentedNorm')
)):
m = axs[i].contourf(
data, levels=ticks, extend='both',
cmap='Mako', norm=norm,
colorbar='b', colorbar_kw={'ticks': ticks},
)
axs[i].format(title=title)
axs.format(suptitle='Linear segmented normalizer demo')
# %%
import proplot as plot
import numpy as np
state = np.random.RandomState(51423)
fig, axs = plot.subplots(ncols=3, nrows=2, axwidth=1.7)
colors = state.rand(15, 12, 3).cumsum(axis=2)
colors /= colors.max()
axs.imshow(colors)
axs.format(
suptitle='Auto figure sizing with grid of images'
)
# %%
import proplot as plot
# Change the reference subplot width
suptitle = 'Effect of subplot width on figure size'
for axwidth in ('4cm', '6cm'):
fig, axs = plot.subplots(ncols=2, axwidth=axwidth,)
axs[0].format(
suptitle=suptitle,
title=f'axwidth = {axwidth}', titleweight='bold',
titleloc='uc', titlecolor='red9',
)
# Change the reference subplot aspect ratio
for aspect in (1, (3, 2)):
fig, axs = plot.subplots(ncols=2, nrows=2, axwidth=1.6, aspect=aspect)
axs[0].format(
suptitle='Effect of subplot aspect ratio on figure size',
title=f'aspect = {aspect}', titleweight='bold',
titleloc='uc', titlecolor='red9',
)
# %%
xlabel, ylabel = 'hue', 'luminance'
xloc, yloc = 60, 20
elif hue is not None:
hsl = np.concatenate((
np.ones((len(lums), len(sats)))[...,None]*hue,
np.repeat(sats[None,:], len(lums), axis=0)[...,None],
np.repeat(lums[:,None], len(sats), axis=1)[...,None],
), axis=2)
suptitle = 'Luminance-saturation cross-section'
xlabel, ylabel = 'luminance', 'saturation'
xloc, yloc = 20, 20
# Make figure, with black indicating invalid values
# Note we invert the x-y ordering for imshow
from . import subplots
fig, axs = subplots(
ncols=3, share=0, axwidth=2, aspect=1, axpad=0.05
)
for ax,space in zip(axs,('hcl','hsl','hpl')):
rgba = np.ones((*hsl.shape[:2][::-1], 4)) # RGBA
for j in range(hsl.shape[0]):
for k in range(hsl.shape[1]):
rgb_jk = to_rgb(hsl[j,k,:].flat, space)
if not all(0 <= c <= 1 for c in rgb_jk):
rgba[k,j,3] = 0 # black cell
else:
rgba[k,j,:3] = rgb_jk
ax.imshow(rgba, origin='lower', aspect='auto')
ax.format(xlabel=xlabel, ylabel=ylabel, suptitle=suptitle,
grid=False, xtickminor=False, ytickminor=False,
xlocator=xloc, ylocator=yloc, facecolor='k',
title=space.upper(), titleweight='bold')
)
for proj, ax in zip(projs, axs):
ax.format(title=proj, titleweight='bold', labels=False)
# %%
import proplot as plot
# Table of basemap projections
projs = [
'cyl', 'merc', 'mill', 'cea', 'gall', 'sinu',
'eck4', 'robin', 'moll', 'kav7', 'hammer', 'mbtfpq',
'geos', 'ortho', 'nsper',
'vandg', 'aea', 'eqdc', 'gnom', 'cass', 'lcc',
'npstere', 'npaeqd', 'nplaea'
]
fig, axs = plot.subplots(ncols=3, nrows=8, basemap=True, width=7, proj=projs)
axs.format(
land=True, labels=False,
suptitle='Table of basemap projections'
)
for proj, ax in zip(projs, axs):
ax.format(title=proj, titleweight='bold', labels=False)
# `~matplotlib.axes.Axes.contourf` plots by simply using ``labels=True``.
# The label text is colored black or white depending on the luminance of
# the underlying grid box or filled contour.
#
# `~proplot.axes.cmap_changer` draws contour labels with
# `~matplotlib.axes.Axes.clabel` and grid box labels with
# `~matplotlib.axes.Axes.text`. You can pass keyword arguments to these
# functions using the `labels_kw` dictionary keyword argument, and change the
# label precision with the `precision` keyword argument. See
# `~proplot.axes.cmap_changer` for details.
# %%
import proplot as plot
import pandas as pd
import numpy as np
fig, axs = plot.subplots(
[[1, 1, 2, 2], [0, 3, 3, 0]],
axwidth=2.2, share=1, span=False, hratios=(1, 0.9)
)
state = np.random.RandomState(51423)
data = state.rand(6, 6)
data = pd.DataFrame(data, index=pd.Index(['a', 'b', 'c', 'd', 'e', 'f']))
axs.format(xlabel='xlabel', ylabel='ylabel', suptitle='Labels demo')
# Heatmap with labeled boxes
ax = axs[0]
m = ax.heatmap(
data, cmap='rocket', labels=True,
precision=2, labels_kw={'weight': 'bold'}
)
ax.format(title='Heatmap plot with labels')
proj = plot.Proj('npaeqd', boundinglat=60, basemap=True)
fig, axs = plot.subplots(ncols=2, axwidth=2.7, proj=('splaea', proj))
axs.format(
land=True, latmax=80, # no gridlines poleward of 80 degrees
suptitle='Zooming into polar projections'
)
axs[0].format(boundinglat=-60, title='Cartopy example')
axs[1].format(title='Basemap example')
# %%
import proplot as plot
# Zooming in on continents
proj1 = plot.Proj('lcc', lon_0=0) # cartopy projection
proj2 = plot.Proj('lcc', lon_0=-100, lat_0=45, width=8e6, height=8e6, basemap=True)
fig, axs = plot.subplots(ncols=2, axwidth=3, proj=(proj1, proj2))
axs.format(suptitle='Zooming into specific regions', land=True)
axs[0].format(lonlim=(-20, 50), latlim=(30, 70), title='Cartopy example')
axs[1].format(lonlines=20, title='Basemap example')
# Zooming to very small scale with degree-minute-second labels
plot.rc.reso = 'hi'
fig, axs = plot.subplots(ncols=2, axwidth=2.5, proj='cyl')
axs.format(
land=True, labels=True,
borders=True, borderscolor='white',
suptitle='Degree-minute-second labels',
)
axs[0].format(lonlim=(-7.5, 2), latlim=(49.5, 59))
axs[1].format(lonlim=(-6, -2), latlim=(54.5, 58.5))
plot.rc.reset()
# %%
import proplot as plot
import numpy as np
import pandas as pd
# Create cycle that loops through 'dashes' Line2D property
cycle = plot.Cycle(dashes=[(1, 0.5), (1, 1.5), (3, 0.5), (3, 1.5)])
# Generate sample data
state = np.random.RandomState(51423)
data = (state.rand(20, 4) - 0.5).cumsum(axis=0)
data = pd.DataFrame(data, columns=pd.Index(['a', 'b', 'c', 'd'], name='label'))
# Plot data
fig, ax = plot.subplots(axwidth=2.6, aspect=1)
ax.format(suptitle='Plot without color cycle')
obj = ax.plot(
data, lw=3, cycle=cycle, legend='ul',
legend_kw={'ncols': 2, 'handlelength': 3}
)
# `~proplot.utils.units` function.
#
# If a sizing argument is numeric, the units are inches or points; if it is
# string, the units are converted to inches or points by
# `~proplot.utils.units`. A table of acceptable units is found in the
# `~proplot.utils.units` documentation. They include centimeters,
# millimeters, pixels,
# `em-heights `__,
# `en-heights `__,
# and `points `__.
# %%
import proplot as plot
import numpy as np
with plot.rc.context(fontsize='12px'):
fig, axs = plot.subplots(
ncols=3, width='15cm', height='3in',
wspace=('10pt', '20pt'), right='10mm'
)
cmap = plot.Colormap('Mono')
cb = fig.colorbar(
cmap, loc='b', extend='both', label='colorbar',
width='2em', extendsize='3em', shrink=0.8,
)
pax = axs[2].panel('r', width='5en')
pax.format(xlim=(0, 1))
axs.format(
suptitle='Arguments with arbitrary units',
xlabel='x axis', ylabel='y axis',
xlim=(0, 1), ylim=(0, 1),
)