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 / 10rounded down to its first non-zero digit, bypolyphys.manage.utils.round_down_first_non_zero(); a tick closer to zero than the tolerance is written as exactly0.0, so-5.6e-17never 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()andline_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
|
Shade one band under each line of ax, in that line's color. |
|
Make one filled |
|
Make one empty |
|
Remove legend and re-create it inside each of axes. |
|
Place the major x ticks of ax every step from lower to upper. |
|
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 underax.lines[i], each an array over that line’s x data; the band is drawn withmatplotlib.axes.Axes.fill_between(). Lines beyondlen(bands)get no band. Time and space are \(O(n_\mathrm{lines} \, n_\mathrm{points})\).- Parameters:
ax (
matplotlib.axes.Axes) – The axes whose lines are shaded, in drawing order.bands (
typing.Sequence[tuple[typing.Any,typing.Any]]) – The lower and upper edge of each band, shape(n_points,)each, matching the x data of the line.alpha (
float) – The opacity of every band.**fill_kwargs (
typing.Any) – Passed to everymatplotlib.axes.Axes.fill_between()call, such aslinewidth.
- Returns:
The bands, in the order of the lines.
- Return type:
- 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
Patchper 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 everyPatch, such asalpha.
- Returns:
The handles, one per label, for the
handlesargument ofmatplotlib.axes.Axes.legend().- Return type:
- 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
Line2Dper 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:
labels (
typing.Sequence[str]) – The legend entries.linestyles (
typing.Union[None,str,typing.Sequence[typing.Any]]) – The line style of each handle, such as'-'or'--'.linewidths (
typing.Union[None,float,typing.Sequence[float]]) – The line width of each handle, in points.markers (
typing.Union[None,str,typing.Sequence[typing.Any]]) – The marker of each handle, such as'o'or'^'.color (
typing.Any) – The color of every handle.**line_kwargs (
typing.Any) – Passed to everyLine2D, such asmarkersize.
- Returns:
The handles, one per label.
- Return type:
- 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:
legend (
matplotlib.legend.Legend) – The legend to move; it is removed from its figure or axes.axes (
typing.Sequence[matplotlib.axes.Axes]) – The axes that receive a copy each.locs (
typing.Sequence[typing.Any]) – One legend location per axes, as thelocargument ofmatplotlib.axes.Axes.legend()takes it.title (
typing.Optional[str]) – A new title; by default the title of legend is kept.**legend_kwargs (
typing.Any) – Passed to everymatplotlib.axes.Axes.legend()call, such asframeon.
- Returns:
The new legends, in the order of axes.
- Return type:
- 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 thanupper - lower.labels (
bool) – Whether the ticks are labeled;Falsehides every label.decimals (
int) – The number of decimals the labels are rounded to.**text_kwargs (
typing.Any) – Passed tomatplotlib.axes.Axes.set_xticklabels(), such asfontsize.
- Returns:
The tick positions, shape
(n_ticks,).- Return type:
- Raises:
ValueError – If
lower >= upper, or step is not positive and smaller thanupper - 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 tomatplotlib.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 thanupper - lower.labels (
bool) – Whether the ticks are labeled.decimals (
int) – The number of decimals the labels are rounded to.**text_kwargs (
typing.Any) – Passed tomatplotlib.axes.Axes.set_yticklabels().
- Returns:
The tick positions, shape
(n_ticks,).- Return type:
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)