polyphys.viz.helpers#

polyphys.viz.helpers#

The polyphys.viz.helpers module holds the matplotlib helpers the studies’ multi-panel figures use: a rule for placing an axis’s ticks, proxy legend handles, a legend moved into chosen panels, and a band shaded under each line. It needs matplotlib, which the viz extra installs, and raises ImportError with that hint when it is missing.

Ticks#

set_xticks() and set_yticks() place the major ticks of one axis by one rule. Given lower, upper, and step:

  • the ticks are \(t_k = \mathrm{lower} + k \, \mathrm{step}\) for \(k = 0, 1, \dots, \lfloor (\mathrm{upper} - \mathrm{lower}) / \mathrm{step} \rfloor\), so the last tick is upper when step divides the span;

  • the tolerance is step / 10 rounded down to its first non-zero digit, by polyphys.manage.utils.round_down_first_non_zero(); a tick closer to zero than the tolerance is written as exactly 0.0, so -5.6e-17 never appears as a label;

  • the axis limits are (lower - tolerance, upper + tolerance), a frame that keeps the first and last ticks off the axes’ edges;

  • the labels are the ticks rounded to decimals places, or hidden.

The ticks are not rounded to multiples of a power of ten; the caller chooses lower, upper, and step with that in mind.

Legends#

  • color_handles() and line_handles() make proxy handles, artists that draw nothing on the axes and exist only to sit in a legend, so a figure can carry one legend for its colors and another for its line styles or markers, whatever the plotting call produced.

  • move_legend_to_axes() takes an existing legend, such as the figure legend a facet grid draws outside its panels, and re-creates it inside chosen panels.

  • band_under_lines() shades a band, such as a confidence interval, under each line already drawn on an axes, in that line’s color.

Examples

>>> import matplotlib
>>> matplotlib.use("Agg")
>>> import matplotlib.pyplot as plt
>>> from polyphys.viz.helpers import color_handles, set_xticks
>>> fig, ax = plt.subplots()
>>> set_xticks(ax, 0.0, 1.0, 0.25)
array([0.  , 0.25, 0.5 , 0.75, 1.  ])
>>> [float(limit) for limit in ax.get_xlim()]
[-0.02, 1.02]
>>> handles = color_handles(["bug", "crowder"], ["#4477AA", "#EE6677"])
>>> [text.get_text() for text in ax.legend(handles=handles).get_texts()]
['bug', 'crowder']
>>> plt.close(fig)

Functions

band_under_lines(ax, bands, *[, alpha])

Shade one band under each line of ax, in that line's color.

color_handles(labels, colors, **patch_kwargs)

Make one filled Patch per label.

line_handles(labels, *[, linestyles, ...])

Make one empty Line2D per label.

move_legend_to_axes(legend, axes, locs, *[, ...])

Remove legend and re-create it inside each of axes.

set_xticks(ax, lower, upper, step, *[, ...])

Place the major x ticks of ax every step from lower to upper.

set_yticks(ax, lower, upper, step, *[, ...])

Place the major y ticks of ax every step from lower to upper.

polyphys.viz.helpers.band_under_lines(ax, bands, *, alpha=0.25, **fill_kwargs)[source]#

Shade one band under each line of ax, in that line’s color.

bands[i] is the pair (lower, upper) of the band under ax.lines[i], each an array over that line’s x data; the band is drawn with matplotlib.axes.Axes.fill_between(). Lines beyond len(bands) get no band. Time and space are \(O(n_\mathrm{lines} \, n_\mathrm{points})\).

Parameters:
Returns:

The bands, in the order of the lines.

Return type:

list[matplotlib.collections.PolyCollection]

Raises:

ValueError – If there are more bands than lines, or a band edge’s length differs from its line’s number of points.

Examples

>>> import matplotlib
>>> matplotlib.use("Agg")
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> _ = ax.plot([0, 1, 2], [1, 1, 1], color="#4477AA")
>>> bands = band_under_lines(ax, [([0.5, 0.5, 0.5], [1.5, 1.5, 1.5])])
>>> len(bands)
1
>>> bands[0].get_facecolor()[0].round(2).tolist()
[0.27, 0.47, 0.67, 0.25]
>>> plt.close(fig)
polyphys.viz.helpers.color_handles(labels, colors, **patch_kwargs)[source]#

Make one filled Patch per label.

The patches are proxy handles for a legend keyed by color. Time and space are \(O(n)\) in the number of labels.

Parameters:
  • labels (typing.Sequence[str]) – The legend entries.

  • colors (typing.Any) – One color for every label, a name or a tuple of numbers such as the RGB triple (0.1, 0.2, 0.3); or a list, or another sequence, with one color per label, in the same order.

  • **patch_kwargs (typing.Any) – Passed to every Patch, such as alpha.

Returns:

The handles, one per label, for the handles argument of matplotlib.axes.Axes.legend().

Return type:

list[matplotlib.patches.Patch]

Raises:

ValueError – If colors is a sequence of colors whose length differs from that of labels.

Examples

>>> patches = color_handles(["low", "high"], ["#4477AA", "#EE6677"],
...                         alpha=0.5)
>>> [patch.get_label() for patch in patches]
['low', 'high']
>>> patches[0].get_alpha()
0.5

One RGB tuple colors every label:

>>> patches = color_handles(["a", "b"], (0.0, 0.5, 1.0))
>>> [patch.get_facecolor()[:3] for patch in patches]
[(0.0, 0.5, 1.0), (0.0, 0.5, 1.0)]
polyphys.viz.helpers.line_handles(labels, *, linestyles=None, linewidths=None, markers=None, color='black', **line_kwargs)[source]#

Make one empty Line2D per label.

The lines are proxy handles for a legend keyed by line style, width, or marker. Each of linestyles, linewidths, and markers is either one value, used for every label, a sequence with one entry per label, or None, which leaves that attribute at matplotlib’s default. One value is a string, a number, or a dash tuple such as (0, (5, 2)); a list, or a tuple of other items, is one entry per label. Time and space are \(O(n)\) in the number of labels.

Parameters:
Returns:

The handles, one per label.

Return type:

list[matplotlib.lines.Line2D]

Raises:

ValueError – If a sequence among linestyles, linewidths, and markers does not have one entry per label.

Examples

>>> lines = line_handles(["ring", "linear"], linestyles=["-", "--"],
...                      markers="o", linewidths=2)
>>> [(line.get_label(), line.get_linestyle(), line.get_marker())
...  for line in lines]
[('ring', '-', 'o'), ('linear', '--', 'o')]
polyphys.viz.helpers.move_legend_to_axes(legend, axes, locs, *, title=None, **legend_kwargs)[source]#

Remove legend and re-create it inside each of axes.

The new legends carry the handles, labels, and title of legend; each replaces the legend its axes had. This moves, for instance, the legend a seaborn facet grid draws beside its panels into one or more panels. Time and space are \(O(n_\mathrm{axes} \, n_\mathrm{entries})\).

Parameters:
Returns:

The new legends, in the order of axes.

Return type:

list[matplotlib.legend.Legend]

Raises:

ValueError – If axes and locs differ in length.

Examples

>>> import matplotlib
>>> matplotlib.use("Agg")
>>> import matplotlib.pyplot as plt
>>> fig, (left, right) = plt.subplots(ncols=2)
>>> _ = left.plot([0, 1], [0, 1], label="rise")
>>> outer = fig.legend(title="curves")
>>> inner = move_legend_to_axes(outer, [right], ["upper left"])
>>> fig.legends
[]
>>> [text.get_text() for text in right.get_legend().get_texts()]
['rise']
>>> right.get_legend().get_title().get_text()
'curves'
>>> plt.close(fig)
polyphys.viz.helpers.set_xticks(ax, lower, upper, step, *, labels=True, decimals=3, **text_kwargs)[source]#

Place the major x ticks of ax every step from lower to upper.

The ticks, the tolerance that frames them, and the labels follow the rule in the module docstring. Time and space are \(O(n)\) in the number of ticks.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes whose x axis is set.

  • lower (float) – The first tick and the largest tick value, in data units; lower < upper.

  • upper (float) – The first tick and the largest tick value, in data units; lower < upper.

  • step (float) – The distance between ticks, positive and smaller than upper - lower.

  • labels (bool) – Whether the ticks are labeled; False hides every label.

  • decimals (int) – The number of decimals the labels are rounded to.

  • **text_kwargs (typing.Any) – Passed to matplotlib.axes.Axes.set_xticklabels(), such as fontsize.

Returns:

The tick positions, shape (n_ticks,).

Return type:

typing.Any

Raises:

ValueError – If lower >= upper, or step is not positive and smaller than upper - lower.

Examples

>>> import matplotlib
>>> matplotlib.use("Agg")
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> set_xticks(ax, -0.2, 0.2, 0.1, decimals=1)
array([-0.2, -0.1,  0. ,  0.1,  0.2])
>>> [label.get_text() for label in ax.get_xticklabels()]
['-0.2', '-0.1', '0.0', '0.1', '0.2']
>>> plt.close(fig)
polyphys.viz.helpers.set_yticks(ax, lower, upper, step, *, labels=True, decimals=3, **text_kwargs)[source]#

Place the major y ticks of ax every step from lower to upper.

The y-axis twin of set_xticks(), with the same rule, parameters, return value, and errors; text_kwargs go to matplotlib.axes.Axes.set_yticklabels().

Parameters:
  • ax (matplotlib.axes.Axes) – The axes whose y axis is set.

  • lower (float) – The first tick and the largest tick value; lower < upper.

  • upper (float) – The first tick and the largest tick value; lower < upper.

  • step (float) – The distance between ticks, positive and smaller than upper - lower.

  • labels (bool) – Whether the ticks are labeled.

  • decimals (int) – The number of decimals the labels are rounded to.

  • **text_kwargs (typing.Any) – Passed to matplotlib.axes.Axes.set_yticklabels().

Returns:

The tick positions, shape (n_ticks,).

Return type:

typing.Any

Examples

>>> import matplotlib
>>> matplotlib.use("Agg")
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> set_yticks(ax, 0.0, 1.0, 0.5, labels=False)
array([0. , 0.5, 1. ])
>>> [float(limit) for limit in ax.get_ylim()]
[-0.05, 1.05]
>>> plt.close(fig)