[TOC]

The basics

Creating figures

ProPlot works by creating a proplot.figure.Figure subclass of the matplotlib figure class Figure, and a proplot.axes.Axes subclass of the matplotlib axes class Axes. All plotting in ProPlot begins by generating an instance of the new figure class filled with instances of the new axes classes using the subplots command, which is modeled after matplotlib.pyplot.subplots. ProPlot’s subplots command can be used as follows:

  • Without any arguments, subplots returns a figure with a single subplot.
  • With ncols or nrows, subplots returns a figure with a simple grid of subplots.
  • With array, subplots returns an arbitrarily complex grid of subplots. This is a 2D array representing a “picture” of the subplot layout, where each unique integer indicates a GridSpec slot that is occupied by the corresponding subplot and 0 indicates an empty space.

In the below examples, we create subplot grids with subplots and modify the axes labels. See the formatting guide and subplots container sections for details.

Note

ProPlot figure backgrounds are only gray when displayed by the matplotlib backend – the default background color is white when the figure is saved. This is done by setting rc[‘figure.facecolor’] to gray, in order to improve contrast when working with figures. ProPlot also makes the default saved figure background transparent by setting rc[‘savefig.transparent’] to True and changes the default rc[‘savefig.format’] from PNG to PDF for the following reasons:

  1. Vector graphic formats are infinitely scalable.
  2. Vector graphic formats are preferred by academic journals.
  3. Most academic journals accept PDF figures alongside the traditional EPS format.
  4. The EPS format does not support transparent graphic elements.

In case you do need raster graphics, ProPlot sets the default rc[‘savefig.dpi’] to 1200 dots per inch, which is recommended by most journals as the minimum resolution for rasterized figures containing lines and text. See the configuration section for how to change any of these settings.

[1]:
# Generate sample dataimport numpy as npstate = np.random.RandomState(51423)data = 2 * (state.rand(100, 5) - 0.5).cumsum(axis=0)
[2]:
# Single subplotimport proplot as plotfig, ax = plot.subplots()ax.plot(data, lw=2)ax.format(suptitle='Single subplot', xlabel='x axis', ylabel='y axis')

img

[3]:
# Simple subplot gridimport proplot as plotfig, axs = plot.subplots(ncols=2)axs[0].plot(data, lw=2)axs[0].format(xticks=20, xtickminor=False)axs.format(    suptitle='Simple subplot grid', title='Title',    xlabel='x axis', ylabel='y axis')

img

[4]:
# Complex gridimport proplot as plotarray = [  # the "picture" (0 == nothing, 1 == subplot A, 2 == subplot B, etc.)    [1, 1, 2, 2],    [0, 3, 3, 0],]fig, axs = plot.subplots(array, axwidth=1.8)axs.format(    abc=True, abcloc='ul', suptitle='Complex subplot grid',    xlabel='xlabel', ylabel='ylabel')axs[2].plot(data, lw=2)
[4]:
(, , , , )

img

[5]:
# Really complex gridimport proplot as plotarray = [  # the "picture" (1 == subplot A, 2 == subplot B, etc.)    [1, 1, 2],    [1, 1, 6],    [3, 4, 4],    [3, 5, 5],]fig, axs = plot.subplots(array, width=5, span=False)axs.format(    suptitle='Really complex subplot grid',    xlabel='xlabel', ylabel='ylabel', abc=True)axs[0].plot(data, lw=2)
[5]:
(, , , , )

img

Plotting data

Matplotlib has two different APIs: an object-oriented API and a MATLAB-style pyplot API (which uses the object-oriented API internally). Plotting in ProPlot is just like plotting in matplotlib with the object-oriented API. Rather than creating a brand new interface, ProPlot simply builds upon the existing matplotlib constructs of the Axes and the Figure by adding new commands and new options to existing commands, without changing the usage or syntax. This means a shallow learning curve for the average matplotlib user.

In the below example, we create a 4-panel figure with the familiar matplotlib commands plot, scatter, pcolormesh, and contourf. See the 1d plotting and 2d plotting sections for details on the plotting features added by ProPlot.

[6]:
import proplot as plotimport numpy as np# Sample dataN = 20state = np.random.RandomState(51423)data = (state.rand(N, N) - 0.5).cumsum(axis=0).cumsum(axis=1)# Example plotscycle = 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')

img

Formatting plots

Every Axes returned by subplots has a format method. This is your one-stop-shop for changing axes settings. Keyword arguments passed to format are interpreted as follows:

  1. Any keyword matching the name of an rc setting is used to update the axes. If the name has “dots”, you can omit them (e.g. titleloc=’left’ to change the rc[‘title.loc’] property). See the configuration section for details.
  2. Valid keywords arguments are passed to proplot.axes.CartesianAxes.format, proplot.axes.PolarAxes.format, or proplot.axes.GeoAxes.format. These change settings that are specific to the axes type. For example:

To change the x axis bounds on a CartesianAxes, use e.g. xlim=(0, 5).

  1. To change the radial bounds on a PolarAxes, use e.g. rlim=(0, 10).
  2. To change the meridional bounds on a GeoAxes, use e.g. lonlim=(-90, 0).
  3. Remaining keyword arguments are passed to the base proplot.axes.Axes.format method. Axes is the base class for all other axes classes. This changes things that are the same for all axes types, like titles and a-b-c subplot labels (e.g. title=’Title’).

The format methods let you use simple shorthands for changing all kinds of settings at once, instead of one-liner setter methods like ax.set_title() and ax.set_xlabel(). They are also integrated with the Locator, Formatter, and Scale constructor functions (see the Cartesian axis settings section for details).

The below example shows the many different keyword arguments accepted by format, and demonstrates how format can be used to succinctly and efficiently customize your plots.

[7]:
import proplot as plotimport numpy as npfig, axs = plot.subplots(ncols=2, nrows=2, share=0, tight=True, axwidth=2)state = np.random.RandomState(51423)N = 60x = np.linspace(1, 10, N)y = (state.rand(N, 5) - 0.5).cumsum(axis=0)axs[0].plot(x, y, linewidth=1.5)axs.format(    suptitle='Format command demo',    abc=True, abcloc='ul', 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=(-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,)

img

Changing rc settings

A special object named rc is created whenever you import ProPlot. rc is similar to the matplotlib rcParams dictionary, but can be used to change both matplotlib settings and ProPlot settings. rc also provides a style parameter that can be used to switch between matplotlib stylesheets. See the configuration section for details.

To modify a setting for just one subplot, you can pass it to the Axes format method. To temporarily modify setting(s) for a block of code, use context. To modify setting(s) for the entire python session, just assign it to the rc object or use update. To reset everything to the default state, use reset. See the below example.

[8]:
import proplot as plotimport numpy as np# Update global settings in several different waysplot.rc.cycle = 'colorblind'plot.rc.color = 'gray6'plot.rc.update({'fontname': 'Source Sans Pro', 'fontsize': 11})plot.rc['figure.facecolor'] = 'gray3'plot.rc.axesfacecolor = 'gray4'# plot.rc.save()  # save the current settings to ~/.proplotrc# Apply settings to figure with context()with plot.rc.context({'suptitle.size': 13}, toplabelcolor='gray6', linewidth=1.5):    fig, axs = plot.subplots(ncols=2, aspect=1, width=6, span=False, sharey=2)# Plot linesN, M = 100, 6state = np.random.RandomState(51423)values = np.arange(1, M + 1)for i, ax in enumerate(axs):    data = np.cumsum(state.rand(N, M) - 0.5, axis=0)    lines = ax.plot(data, linewidth=3, cycle='Grays')# Apply settings to axes with format()axs.format(    grid=False, xlabel='x label', ylabel='y label',    collabels=['Column label 1', 'Column label 2'],    suptitle='Rc settings demo',    suptitlecolor='gray7',    abc=True, abcloc='l', abcstyle='A)',    title='Title', titleloc='r', titlecolor='gray7')ay = axs[-1].twinx()ay.format(ycolor='red', linewidth=1.5, ylabel='secondary axis')ay.plot((state.rand(100) - 0.2).cumsum(), color='r', lw=3)# Reset persistent modifications from head of cellplot.rc.reset()

img

[9]:
import proplot as plotimport numpy as np# plot.rc.style = 'style'  # set the style everywhere# Set up figurestyles = ('ggplot', 'seaborn', '538', 'bmh')state = np.random.RandomState(51423)data = state.rand(10, 5)fig, axs = plot.subplots(ncols=2, nrows=2, span=False, share=False)# Apply different styles to different axes with format()axs.format(suptitle='Stylesheets demo')for ax, style in zip(axs, styles):    ax.format(style=style, xlabel='xlabel', ylabel='ylabel', title=style)    ax.plot(data, linewidth=3)

img

Subplots containers

Instead of an ndarray of axes, subplots returns a SubplotsContainer instance. This container behaves like an Axes object when it contains just one axes, and behaves like a list otherwise. It supports both 1D indexing (e.g. axs[1]) and 2D indexing (e.g. axs[0, 1]), and is row-major by default. Slicing a SubplotsContainer returns another container (e.g. axs[:, 0]), and Axes methods can be called simultaneously for all axes in the container by calling the method from the container (e.g. axs.format(abc=True)).

In the below example, the SubplotsContainer returned by subplots is used to cusomtize several axes at once with proplot.axes.Axes.format.

[10]:
import proplot as plotimport numpy as npstate = np.random.RandomState(51423)fig, axs = plot.subplots(ncols=4, nrows=4, axwidth=1.2)axs.format(    xlabel='xlabel', ylabel='ylabel', suptitle='SubplotsContainer demo',    grid=False, xlim=(0, 50), ylim=(-4, 4))# Various ways to select subplots in the containeraxs[:, 0].format(facecolor='blush', color='gray7', linewidth=1)axs[0, :].format(facecolor='sky blue', color='gray7', linewidth=1)axs[0].format(color='black', facecolor='gray5', linewidth=1.4)axs[1:, 1:].format(facecolor='gray1')for ax in axs[1:, 1:]:    ax.plot((state.rand(50, 5) - 0.5).cumsum(axis=0), cycle='Grays', lw=2)

img