• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

python-control / python-control / 43336464487

13 Nov 2026 12:21AM UTC coverage: 94.757% (+0.01%) from 94.747%
43336464487

Pull #1274

github

web-flow
Merge ec4fd524c into bfe9380ee
Pull Request #1274: DOC: fix docstring parameters that the functions do not accept

9994 of 10547 relevant lines covered (94.76%)

8.28 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.97
control/ctrlplot.py
1
# ctrlplot.py - utility functions for plotting
2
# RMM, 14 Jun 2024
3
#
4

5
"""Utility functions for plotting.
6

7
This module contains a collection of functions that are used by
8
various plotting functions.
9

10
"""
11

12
# Code pattern for control system plotting functions:
13
#
14
# def name_plot(sysdata, *fmt, plot=None, **kwargs):
15
#     # Process keywords and set defaults
16
#     ax = kwargs.pop('ax', None)
17
#     color = kwargs.pop('color', None)
18
#     label = kwargs.pop('label', None)
19
#     rcParams = config._get_param('ctrlplot', 'rcParams', kwargs, pop=True)
20
#
21
#     # Make sure all keyword arguments were processed (if not checked later)
22
#     if kwargs:
23
#         raise TypeError("unrecognized keywords: ", str(kwargs))
24
#
25
#     # Process the data (including generating responses for systems)
26
#     sysdata = list(sysdata)
27
#     if any([isinstance(sys, InputOutputSystem) for sys in sysdata]):
28
#         data = name_response(sysdata)
29
#     nrows = max([data.noutputs for data in sysdata])
30
#     ncols = max([data.ninputs for data in sysdata])
31
#
32
#     # Legacy processing of plot keyword
33
#     if plot is False:
34
#         return data.x, data.y
35
#
36
#     # Figure out the shape of the plot and find/create axes
37
#     fig, ax_array = _process_ax_keyword(ax, (nrows, ncols), rcParams)
38
#     legend_loc, legend_map, show_legend = _process_legend_keywords(
39
#         kwargs, (nrows, ncols), 'center right')
40
#
41
#     # Customize axes (curvilinear grids, shared axes, etc)
42
#
43
#     # Plot the data
44
#     lines = np.empty(ax_array.shape, dtype=object)
45
#     for i in range(ax_array.shape[0]):
46
#         for j in range(ax_array.shape[1]):
47
#             lines[i, j] = []
48
#     line_labels = _process_line_labels(label, ntraces, nrows, ncols)
49
#     color_offset, color_cycle = _get_color_offset(ax)
50
#     for i, j in itertools.product(range(nrows), range(ncols)):
51
#         ax = ax_array[i, j]
52
#         for k in range(ntraces):
53
#             if color is None:
54
#                 color = _get_color(
55
#                     color, fmt=fmt, offset=k, color_cycle=color_cycle)
56
#             label = line_labels[k, i, j]
57
#             lines[i, j] += ax.plot(data.x, data.y, color=color, label=label)
58
#
59
#     # Customize and label the axes
60
#     for i, j in itertools.product(range(nrows), range(ncols)):
61
#         ax_array[i, j].set_xlabel("x label")
62
#         ax_array[i, j].set_ylabel("y label")
63
#
64
#     # Create legends
65
#     if show_legend != False:
66
#         legend_array = np.full(ax_array.shape, None, dtype=object)
67
#         for i, j in itertools.product(range(nrows), range(ncols)):
68
#             if legend_map[i, j] is not None:
69
#                 lines = ax_array[i, j].get_lines()
70
#                 labels = _make_legend_labels(lines)
71
#                 if len(labels) > 1:
72
#                     legend_array[i, j] = ax.legend(
73
#                         lines, labels, loc=legend_map[i, j])
74
#     else:
75
#         legend_array = None
76
#
77
#     # Update the plot title (only if ax was not given)
78
#     sysnames = [response.sysname for response in data]
79
#     if ax is None and title is None:
80
#         title = "Name plot for " + ", ".join(sysnames)
81
#         _update_plot_title(title, fig, rcParams=rcParams)
82
#     elif ax == None:
83
#         _update_plot_title(title, fig, rcParams=rcParams, use_existing=False)
84
#
85
#     # Legacy processing of plot keyword
86
#     if plot is True:
87
#         return data
88
#
89
#     return ControlPlot(lines, ax_array, fig, legend=legend_map)
90

91
import itertools
9 ✔
92
import warnings
9 ✔
93
from os.path import commonprefix
9 ✔
94

95
import matplotlib as mpl
9 ✔
96
import matplotlib.pyplot as plt
9 ✔
97
import numpy as np
9 ✔
98

99
from . import config
9 ✔
100

101
__all__ = [
9 ✔
102
    'ControlPlot', 'suptitle', 'get_plot_axes', 'pole_zero_subplots',
103
    'rcParams', 'reset_rcParams']
104

105
#
106
# Style parameters
107
#
108

109
rcParams_default = {
9 ✔
110
    'axes.labelsize': 'small',
111
    'axes.titlesize': 'small',
112
    'figure.titlesize': 'medium',
113
    'legend.fontsize': 'x-small',
114
    'xtick.labelsize': 'small',
115
    'ytick.labelsize': 'small',
116
}
117
_ctrlplot_rcParams = rcParams_default.copy()    # provide access inside module
9 ✔
118
rcParams = _ctrlplot_rcParams                   # provide access outside module
9 ✔
119

120
_ctrlplot_defaults = {'ctrlplot.rcParams': _ctrlplot_rcParams}
9 ✔
121

122

123
#
124
# Control figure
125
#
126

127
class ControlPlot():
9 ✔
128
    """Return class for control platting functions.
129

130
    This class is used as the return type for control plotting functions.
131
    It contains the information required to access portions of the plot
132
    that the user might want to adjust, as well as providing methods to
133
    modify some of the properties of the plot.
134

135
    A control figure consists of a `matplotlib.figure.Figure` with
136
    an array of `matplotlib.axes.Axes`.  Each axes in the figure has
137
    a number of lines that represent the data for the plot.  There may also
138
    be a legend present in one or more of the axes.
139

140
    Parameters
141
    ----------
142
    lines : array of list of `matplotlib.lines.Line2D`
143
        Array of Line2D objects for each line in the plot.  Generally, the
144
        shape of the array matches the subplots shape and the value of the
145
        array is a list of Line2D objects in that subplot.  Some plotting
146
        functions will return variants of this structure, as described in
147
        the individual documentation for the functions.
148
    axes : 2D array of `matplotlib.axes.Axes`
149
        Array of Axes objects for each subplot in the plot.
150
    figure : `matplotlib.figure.Figure`
151
        Figure on which the Axes are drawn.
152
    legend : `matplotlib.legend.Legend` (instance or ndarray)
153
        Legend object(s) for the plot.  If more than one legend is
154
        included, this will be an array with each entry being either None
155
        (for no legend) or a legend object.
156

157
    """
158
    def __init__(self, lines, axes=None, figure=None, legend=None):
9 ✔
159
        self.lines = lines
9 ✔
160
        if axes is None:
9 ✔
161
            _get_axes = np.vectorize(lambda lines: lines[0].axes)
9 ✔
162
            axes = _get_axes(lines)
9 ✔
163
        self.axes = np.atleast_2d(axes)
9 ✔
164
        if figure is None:
9 ✔
165
            figure = self.axes[0, 0].figure
9 ✔
166
        self.figure = figure
9 ✔
167
        self.legend = legend
9 ✔
168

169
    # Implement methods and properties to allow legacy interface (np.array)
170
    __iter__ = lambda self: self.lines
9 ✔
171
    __len__ = lambda self: len(self.lines)
9 ✔
172
    def __getitem__(self, item):
9 ✔
173
        warnings.warn(
9 ✔
174
            "return of Line2D objects from plot function is deprecated in "
175
            "favor of ControlPlot; use out.lines to access Line2D objects",
176
            category=FutureWarning)
177
        return self.lines[item]
9 ✔
178
    def __setitem__(self, item, val):
9 ✔
179
        self.lines[item] = val
×
180
    shape = property(lambda self: self.lines.shape, None)
9 ✔
181
    def reshape(self, *args):
9 ✔
182
        """Reshape lines array (legacy)."""
183
        return self.lines.reshape(*args)
9 ✔
184

185
    def set_plot_title(self, title, frame='axes'):
9 ✔
186
        """Set the title for a control plot.
187

188
        This is a wrapper for the matplotlib `suptitle` function, but by
189
        setting `frame` to 'axes' (default) then the title is centered on
190
        the midpoint of the axes in the figure, rather than the center of
191
        the figure.  This usually looks better (particularly with
192
        multi-panel plots), though it takes longer to render.
193

194
        Parameters
195
        ----------
196
        title : str
197
            Title text.
198
        frame : str, optional
199
            Coordinate frame for centering: 'axes' (default) or 'figure'.
200

201
        """
202
        _update_plot_title(
9 ✔
203
            title, fig=self.figure, frame=frame, use_existing=False)
204

205
#
206
# User functions
207
#
208
# The functions below can be used by users to modify control plots or get
209
# information about them.
210
#
211

212
def suptitle(
9 ✔
213
        title, fig=None, frame='axes', **kwargs):
214
    """Add a centered title to a figure.
215

216
    .. deprecated:: 0.10.1
217
        Use `ControlPlot.set_plot_title`.
218

219
    """
220
    warnings.warn(
9 ✔
221
        "suptitle() is deprecated; use cplt.set_plot_title()", FutureWarning)
222
    _update_plot_title(
9 ✔
223
        title, fig=fig, frame=frame, use_existing=False, **kwargs)
224

225

226
# Create vectorized function to find axes from lines
227
def get_plot_axes(line_array):
9 ✔
228
    """Get a list of axes from an array of lines.
229

230
    .. deprecated:: 0.10.1
231
        This function will be removed in a future version of python-control.
232
        Use `cplt.axes` to obtain axes for an instance of `ControlPlot`.
233

234
    This function can be used to return the set of axes corresponding
235
    to the line array that is returned by `time_response_plot`.  This
236
    is useful for generating an axes array that can be passed to
237
    subsequent plotting calls.
238

239
    Parameters
240
    ----------
241
    line_array : array of list of `matplotlib.lines.Line2D`
242
        A 2D array with elements corresponding to a list of lines appearing
243
        in an axes, matching the return type of a time response data plot.
244

245
    Returns
246
    -------
247
    axes_array : array of list of `matplotlib.axes.Axes`
248
        A 2D array with elements corresponding to the Axes associated with
249
        the lines in `line_array`.
250

251
    Notes
252
    -----
253
    Only the first element of each array entry is used to determine the axes.
254

255
    """
256
    warnings.warn(
9 ✔
257
        "get_plot_axes() is deprecated; use cplt.axes()", FutureWarning)
258
    _get_axes = np.vectorize(lambda lines: lines[0].axes)
9 ✔
259
    if isinstance(line_array, ControlPlot):
9 ✔
260
        return _get_axes(line_array.lines)
9 ✔
261
    else:
262
        return _get_axes(line_array)
9 ✔
263

264

265
def pole_zero_subplots(
9 ✔
266
        nrows, ncols, grid=None, dt=None, fig=None, scaling=None,
267
        rcParams=None):
268
    """Create axes for pole/zero plot.
269

270
    Parameters
271
    ----------
272
    nrows, ncols : int
273
        Number of rows and columns.
274
    grid : True, False, or 'empty', optional
275
        Grid style to use.  Can also be a list, in which case each subplot
276
        will have a different style (columns then rows).
277
    dt : timebase, option
278
        Timebase for each subplot (or a list of timebases).
279
    scaling : 'auto', 'equal', or None
280
        Scaling to apply to the subplots.
281
    fig : `matplotlib.figure.Figure`
282
        Figure to use for creating subplots.
283
    rcParams : dict
284
        Override the default parameters used for generating plots.
285
        Default is set by `config.defaults['ctrlplot.rcParams']`.
286

287
    Returns
288
    -------
289
    ax_array : ndarray
290
        2D array of axes.
291

292
    """
293
    from .grid import nogrid, sgrid, zgrid
9 ✔
294
    from .iosys import isctime
9 ✔
295

296
    if fig is None:
9 ✔
297
        fig = plt.gcf()
9 ✔
298
    rcParams = config._get_param('ctrlplot', 'rcParams', rcParams)
9 ✔
299

300
    if not isinstance(grid, list):
9 ✔
301
        grid = [grid] * nrows * ncols
9 ✔
302
    if not isinstance(dt, list):
9 ✔
303
        dt = [dt] * nrows * ncols
9 ✔
304

305
    ax_array = np.full((nrows, ncols), None)
9 ✔
306
    index = 0
9 ✔
307
    with plt.rc_context(rcParams):
9 ✔
308
        for row, col in itertools.product(range(nrows), range(ncols)):
9 ✔
309
            match grid[index], isctime(dt=dt[index]):
9 ✔
310
                case 'empty', _:        # empty grid
9 ✔
311
                    ax_array[row, col] = fig.add_subplot(nrows, ncols, index+1)
9 ✔
312

313
                case True, True:        # continuous-time grid
9 ✔
314
                    ax_array[row, col], _ = sgrid(
9 ✔
315
                        (nrows, ncols, index+1), scaling=scaling)
316

317
                case True, False:       # discrete-time grid
9 ✔
318
                    ax_array[row, col] = fig.add_subplot(nrows, ncols, index+1)
9 ✔
319
                    zgrid(ax=ax_array[row, col], scaling=scaling)
9 ✔
320

321
                case False | None, _:   # no grid (just stability boundaries)
9 ✔
322
                    ax_array[row, col] = fig.add_subplot(nrows, ncols, index+1)
9 ✔
323
                    nogrid(
9 ✔
324
                        ax=ax_array[row, col], dt=dt[index], scaling=scaling)
325
            index += 1
9 ✔
326
    return ax_array
9 ✔
327

328

329
def reset_rcParams():
9 ✔
330
    """Reset rcParams to default values for control plots."""
331
    _ctrlplot_rcParams.update(rcParams_default)
9 ✔
332

333

334
#
335
# Utility functions
336
#
337
# These functions are used by plotting routines to provide a consistent way
338
# of processing and displaying information.
339
#
340

341
def _process_ax_keyword(
9 ✔
342
        axs, shape=(1, 1), rcParams=None, squeeze=False, clear_text=False,
343
        create_axes=True, sharex=False, sharey=False):
344
    """Process ax keyword to plotting commands.
345

346
    This function processes the `ax` keyword to plotting commands.  If no
347
    ax keyword is passed, the current figure is checked to see if it has
348
    the correct shape.  If the shape matches the desired shape, then the
349
    current figure and axes are returned.  Otherwise a new figure is
350
    created with axes of the desired shape.
351

352
    If `create_axes` is False and a new/empty figure is returned, then `axs`
353
    is an array of the proper shape but None for each element.  This allows
354
    the calling function to do the actual axis creation (needed for
355
    curvilinear grids that use the AxisArtist module).
356

357
    Legacy behavior: some of the older plotting commands use an axes label
358
    to identify the proper axes for plotting.  This behavior is supported
359
    through the use of the label keyword, but will only work if shape ==
360
    (1, 1) and squeeze == True.
361

362
    """
363
    if axs is None:
9 ✔
364
        fig = plt.gcf()         # get current figure (or create new one)
9 ✔
365
        axs = fig.get_axes()
9 ✔
366

367
        # Check to see if axes are the right shape; if not, create new figure
368
        # Note: can't actually check the shape, just the total number of axes
369
        if len(axs) != np.prod(shape):
9 ✔
370
            with plt.rc_context(rcParams):
9 ✔
371
                if len(axs) != 0 and create_axes:
9 ✔
372
                    # Create a new figure
373
                    fig, axs = plt.subplots(
9 ✔
374
                        *shape, sharex=sharex, sharey=sharey, squeeze=False)
375
                elif create_axes:
9 ✔
376
                    # Create new axes on (empty) figure
377
                    axs = fig.subplots(
9 ✔
378
                        *shape, sharex=sharex, sharey=sharey, squeeze=False)
379
                else:
380
                    # Create an empty array and let user create axes
381
                    axs = np.full(shape, None)
9 ✔
382
            if create_axes:     # if not creating axes, leave these to caller
9 ✔
383
                fig.set_layout_engine('tight')
9 ✔
384
                fig.align_labels()
9 ✔
385

386
        else:
387
            # Use the existing axes, properly reshaped
388
            axs = np.asarray(axs).reshape(*shape)
9 ✔
389

390
            if clear_text:
9 ✔
391
                # Clear out any old text from the current figure
392
                for text in fig.texts:
9 ✔
393
                    text.set_visible(False)     # turn off the text
9 ✔
394
                    del text                    # get rid of it completely
9 ✔
395
    else:
396
        axs = np.atleast_1d(axs)
9 ✔
397
        try:
9 ✔
398
            axs = axs.reshape(shape)
9 ✔
399
        except ValueError:
9 ✔
400
            raise ValueError(
9 ✔
401
                "specified axes are not the right shape; "
402
                f"got {axs.shape} but expecting {shape}")
403
        fig = axs[0, 0].figure
9 ✔
404

405
    # Process the squeeze keyword
406
    if squeeze and shape == (1, 1):
9 ✔
407
        axs = axs[0, 0]         # Just return the single axes object
9 ✔
408
    elif squeeze:
9 ✔
409
        axs = axs.squeeze()
×
410

411
    return fig, axs
9 ✔
412

413

414
# Turn label keyword into array indexed by trace, output, input
415
# TODO: move to ctrlutil.py and update parameter names to reflect general use
416
def _process_line_labels(label, ntraces=1, ninputs=0, noutputs=0):
9 ✔
417
    if label is None:
9 ✔
418
        return None
9 ✔
419

420
    if isinstance(label, str):
9 ✔
421
        label = [label] * ntraces          # single label for all traces
9 ✔
422

423
    # Convert to an ndarray, if not done already
424
    try:
9 ✔
425
        line_labels = np.asarray(label)
9 ✔
426
    except ValueError:
×
427
        raise ValueError("label must be a string or array_like")
×
428

429
    # Turn the data into a 3D array of appropriate shape
430
    # TODO: allow more sophisticated broadcasting (and error checking)
431
    try:
9 ✔
432
        if ninputs > 0 and noutputs > 0:
9 ✔
433
            if line_labels.ndim == 1 and line_labels.size == ntraces:
9 ✔
434
                line_labels = line_labels.reshape(ntraces, 1, 1)
9 ✔
435
                line_labels = np.broadcast_to(
9 ✔
436
                    line_labels, (ntraces, ninputs, noutputs))
437
            else:
438
                line_labels = line_labels.reshape(ntraces, ninputs, noutputs)
9 ✔
439
    except ValueError:
×
440
        if line_labels.shape[0] != ntraces:
×
441
            raise ValueError("number of labels must match number of traces")
×
442
        else:
443
            raise ValueError("labels must be given for each input/output pair")
×
444

445
    return line_labels
9 ✔
446

447

448
# Get labels for all lines in an axes
449
def _get_line_labels(ax, use_color=True):
9 ✔
450
    labels_colors, lines = [], []
9 ✔
451
    last_color, counter = None, 0       # label unknown systems
9 ✔
452
    for i, line in enumerate(ax.get_lines()):
9 ✔
453
        label = line.get_label()
9 ✔
454
        color = line.get_color()
9 ✔
455
        if use_color and label.startswith("Unknown"):
9 ✔
456
            label = f"Unknown-{counter}"
×
457
            if last_color != color:
×
458
                counter += 1
×
459
            last_color = color
×
460
        elif label[0] == '_':
9 ✔
461
            continue
9 ✔
462

463
        if (label, color) not in labels_colors:
9 ✔
464
            lines.append(line)
9 ✔
465
            labels_colors.append((label, color))
9 ✔
466

467
    return lines, [label for label, color in labels_colors]
9 ✔
468

469

470
def _process_legend_keywords(
9 ✔
471
        kwargs, shape=None, default_loc='center right'):
472
    legend_loc = kwargs.pop('legend_loc', None)
9 ✔
473
    if shape is None and 'legend_map' in kwargs:
9 ✔
474
        raise TypeError("unexpected keyword argument 'legend_map'")
9 ✔
475
    else:
476
        legend_map = kwargs.pop('legend_map', None)
9 ✔
477
    show_legend = kwargs.pop('show_legend', None)
9 ✔
478

479
    # If legend_loc or legend_map were given, always show the legend
480
    if legend_loc is False or legend_map is False:
9 ✔
481
        if show_legend is True:
9 ✔
482
            warnings.warn(
×
483
                "show_legend ignored; legend_loc or legend_map was given")
484
        show_legend = False
9 ✔
485
        legend_loc = legend_map = None
9 ✔
486
    elif legend_loc is not None or legend_map is not None:
9 ✔
487
        if show_legend is False:
9 ✔
488
            warnings.warn(
×
489
                "show_legend ignored; legend_loc or legend_map was given")
490
        show_legend = True
9 ✔
491

492
    if legend_loc is None:
9 ✔
493
        legend_loc = default_loc
9 ✔
494
    elif not isinstance(legend_loc, (int, str)):
9 ✔
495
        raise ValueError("legend_loc must be string or int")
×
496

497
    # Make sure the legend map is the right size
498
    if legend_map is not None:
9 ✔
499
        legend_map = np.atleast_2d(legend_map)
9 ✔
500
        if legend_map.shape != shape:
9 ✔
501
            raise ValueError("legend_map shape just match axes shape")
×
502

503
    return legend_loc, legend_map, show_legend
9 ✔
504

505

506
# Utility function to make legend labels
507
def _make_legend_labels(labels, ignore_common=False):
9 ✔
508
    if len(labels) == 1:
9 ✔
509
        return labels
9 ✔
510

511
    # Look for a common prefix (up to a space)
512
    common_prefix = commonprefix(labels)
9 ✔
513
    last_space = common_prefix.rfind(', ')
9 ✔
514
    if last_space < 0 or ignore_common:
9 ✔
515
        common_prefix = ''
9 ✔
516
    elif last_space > 0:
9 ✔
517
        common_prefix = common_prefix[:last_space + 2]
9 ✔
518
    prefix_len = len(common_prefix)
9 ✔
519

520
    # Look for a common suffix (up to a space)
521
    common_suffix = commonprefix(
9 ✔
522
        [label[::-1] for label in labels])[::-1]
523
    suffix_len = len(common_suffix)
9 ✔
524
    # Only chop things off after a comma or space
525
    while suffix_len > 0 and common_suffix[-suffix_len] != ',':
9 ✔
526
        suffix_len -= 1
9 ✔
527

528
    # Strip the labels of common information
529
    if suffix_len > 0 and not ignore_common:
9 ✔
530
        labels = [label[prefix_len:-suffix_len] for label in labels]
9 ✔
531
    else:
532
        labels = [label[prefix_len:] for label in labels]
9 ✔
533

534
    return labels
9 ✔
535

536

537
def _update_plot_title(
9 ✔
538
        title, fig=None, frame='axes', use_existing=True, **kwargs):
539
    """Set or extend the centered title of a figure.
540

541
    Parameters
542
    ----------
543
    title : str
544
        Title text.
545
    fig : Figure, optional
546
        Matplotlib figure.  Defaults to the current figure.
547
    frame : str, optional
548
        Coordinate frame for centering: 'axes' (default) or 'figure'.
549
    use_existing : bool, optional
550
        If True (default), extend the figure's existing title instead of
551
        replacing it.
552
    **kwargs : `matplotlib.pyplot.suptitle` keywords, optional
553
        Additional keywords (passed to matplotlib).
554

555
    """
556
    if title is False or title is None:
9 ✔
557
        return
9 ✔
558
    if fig is None:
9 ✔
559
        fig = plt.gcf()
9 ✔
560
    rcParams = config._get_param('ctrlplot', 'rcParams', kwargs, pop=True)
9 ✔
561

562
    if use_existing:
9 ✔
563
        # Get the current title, if it exists
564
        old_title = None if fig._suptitle is None else fig._suptitle._text
9 ✔
565

566
        if old_title is not None:
9 ✔
567
            # Find the common part of the titles
568
            common_prefix = commonprefix([old_title, title])
9 ✔
569

570
            # Back up to the last space
571
            last_space = common_prefix.rfind(' ')
9 ✔
572
            if last_space > 0:
9 ✔
573
                common_prefix = common_prefix[:last_space]
9 ✔
574
            common_len = len(common_prefix)
9 ✔
575

576
            # Add the new part of the title (usually the system name)
577
            if old_title[common_len:] != title[common_len:]:
9 ✔
578
                separator = ',' if len(common_prefix) > 0 else ';'
9 ✔
579
                title = old_title + separator + title[common_len:]
9 ✔
580

581
    if frame == 'figure':
9 ✔
582
        with plt.rc_context(rcParams):
9 ✔
583
            fig.suptitle(title, **kwargs)
9 ✔
584

585
    elif frame == 'axes':
9 ✔
586
        with plt.rc_context(rcParams):
9 ✔
587
            fig.suptitle(title, **kwargs)           # Place title in center
9 ✔
588
            plt.tight_layout()                      # Put everything into place
9 ✔
589
            xc, _ = _find_axes_center(fig, fig.get_axes())
9 ✔
590
            fig.suptitle(title, x=xc, **kwargs)     # Redraw title, centered
9 ✔
591

592
    else:
593
        raise ValueError(f"unknown frame '{frame}'")
9 ✔
594

595

596
def _find_axes_center(fig, axs):
9 ✔
597
    """Find the midpoint between axes in display coordinates.
598

599
    This function finds the middle of a plot as defined by a set of axes.
600

601
    """
602
    inv_transform = fig.transFigure.inverted()
9 ✔
603
    xlim = ylim = [1, 0]
9 ✔
604
    for ax in axs:
9 ✔
605
        ll = inv_transform.transform(ax.transAxes.transform((0, 0)))
9 ✔
606
        ur = inv_transform.transform(ax.transAxes.transform((1, 1)))
9 ✔
607

608
        xlim = [min(ll[0], xlim[0]), max(ur[0], xlim[1])]
9 ✔
609
        ylim = [min(ll[1], ylim[0]), max(ur[1], ylim[1])]
9 ✔
610

611
    return (np.sum(xlim)/2, np.sum(ylim)/2)
9 ✔
612

613

614
# Internal function to add arrows to a curve
615
def _add_arrows_to_line2D(
9 ✔
616
        axes, line, arrow_locs=[0.2, 0.4, 0.6, 0.8],
617
        arrowstyle='-|>', arrowsize=1, dir=1):
618
    """
619
    Add arrows to a matplotlib.lines.Line2D at selected locations.
620

621
    Parameters
622
    ----------
623
    axes: Axes object as returned by axes command (or gca)
624
    line: Line2D object as returned by plot command
625
    arrow_locs: list of locations where to insert arrows, % of total length
626
    arrowstyle: style of the arrow
627
    arrowsize: size of the arrow
628

629
    Returns
630
    -------
631
    arrows : list of arrows
632

633
    Notes
634
    -----
635
    Based on https://stackoverflow.com/questions/26911898/
636

637
    """
638
    # Get the coordinates of the line, in plot coordinates
639
    if not isinstance(line, mpl.lines.Line2D):
9 ✔
640
        raise ValueError("expected a matplotlib.lines.Line2D object")
×
641
    x, y = line.get_xdata(), line.get_ydata()
9 ✔
642

643
    # Determine the arrow properties
644
    arrow_kw = {"arrowstyle": arrowstyle}
9 ✔
645

646
    color = line.get_color()
9 ✔
647
    use_multicolor_lines = isinstance(color, np.ndarray)
9 ✔
648
    if use_multicolor_lines:
9 ✔
649
        raise NotImplementedError("multi-color lines not supported")
650
    else:
651
        arrow_kw['color'] = color
9 ✔
652

653
    linewidth = line.get_linewidth()
9 ✔
654
    if isinstance(linewidth, np.ndarray):
9 ✔
655
        raise NotImplementedError("multi-width lines not supported")
656
    else:
657
        arrow_kw['linewidth'] = linewidth
9 ✔
658

659
    # Figure out the size of the axes (length of diagonal)
660
    xlim, ylim = axes.get_xlim(), axes.get_ylim()
9 ✔
661
    ul, lr = np.array([xlim[0], ylim[0]]), np.array([xlim[1], ylim[1]])
9 ✔
662
    diag = np.linalg.norm(ul - lr)
9 ✔
663

664
    # Compute the arc length along the curve
665
    s = np.cumsum(np.sqrt(np.diff(x) ** 2 + np.diff(y) ** 2))
9 ✔
666

667
    # Truncate the number of arrows if the curve is short
668
    # TODO: figure out a smarter way to do this
669
    frac = min(s[-1] / diag, 1)
9 ✔
670
    if len(arrow_locs) and frac < 0.05:
9 ✔
671
        arrow_locs = []         # too short; no arrows at all
9 ✔
672
    elif len(arrow_locs) and frac < 0.2:
9 ✔
673
        arrow_locs = [0.5]      # single arrow in the middle
9 ✔
674

675
    # Plot the arrows (and return list if patches)
676
    arrows = []
9 ✔
677
    for loc in arrow_locs:
9 ✔
678
        n = np.searchsorted(s, s[-1] * loc)
9 ✔
679

680
        if dir == 1 and n == 0:
9 ✔
681
            # Move the arrow forward by one if it is at start of a segment
682
            n = 1
9 ✔
683

684
        # Place the head of the arrow at the desired location
685
        arrow_head = [x[n], y[n]]
9 ✔
686
        arrow_tail = [x[n - dir], y[n - dir]]
9 ✔
687

688
        p = mpl.patches.FancyArrowPatch(
9 ✔
689
            arrow_tail, arrow_head, transform=axes.transData, lw=0,
690
            **arrow_kw)
691
        axes.add_patch(p)
9 ✔
692
        arrows.append(p)
9 ✔
693
    return arrows
9 ✔
694

695

696
def _get_color_offset(ax, color_cycle=None):
9 ✔
697
    """Get color offset based on current lines.
698

699
    This function determines that the current offset is for the next color
700
    to use based on current colors in a plot.
701

702
    Parameters
703
    ----------
704
    ax : `matplotlib.axes.Axes`
705
        Axes containing already plotted lines.
706
    color_cycle : list of matplotlib color specs, optional
707
        Colors to use in plotting lines.  Defaults to matplotlib rcParams
708
        color cycle.
709

710
    Returns
711
    -------
712
    color_offset : matplotlib color spec
713
        Starting color for next line to be drawn.
714
    color_cycle : list of matplotlib color specs
715
        Color cycle used to determine colors.
716

717
    """
718
    if color_cycle is None:
9 ✔
719
        color_cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']
9 ✔
720

721
    color_offset = 0
9 ✔
722
    if len(ax.lines) > 0:
9 ✔
723
        last_color = ax.lines[-1].get_color()
9 ✔
724
        if last_color in color_cycle:
9 ✔
725
            color_offset = color_cycle.index(last_color) + 1
9 ✔
726

727
    return color_offset % len(color_cycle), color_cycle
9 ✔
728

729

730
def _get_color(
9 ✔
731
        colorspec, offset=None, fmt=None, ax=None, lines=None,
732
        color_cycle=None):
733
    """Get color to use for plotting line.
734

735
    This function returns the color to be used for the line to be drawn (or
736
    None if the default color cycle for the axes should be used).
737

738
    Parameters
739
    ----------
740
    colorspec : matplotlib color specification
741
        User-specified color (or None).
742
    offset : int, optional
743
        Offset into the color cycle (for multi-trace plots).
744
    fmt : str, optional
745
        Format string passed to plotting command.
746
    ax : `matplotlib.axes.Axes`, optional
747
        Axes containing already plotted lines.
748
    lines : list of matplotlib.lines.Line2D, optional
749
        List of plotted lines.  If not given, use ax.get_lines().
750
    color_cycle : list of matplotlib color specs, optional
751
        Colors to use in plotting lines.  Defaults to matplotlib rcParams
752
        color cycle.
753

754
    Returns
755
    -------
756
    color : matplotlib color spec
757
        Color to use for this line (or None for matplotlib default).
758

759
    """
760
    # See if the color was explicitly specified by the user
761
    if isinstance(colorspec, dict):
9 ✔
762
        if 'color' in colorspec:
9 ✔
763
            return colorspec.pop('color')
9 ✔
764
    elif fmt is not None and \
9 ✔
765
         [isinstance(arg, str) and
766
          any([c in arg for c in "bgrcmykw#"]) for arg in fmt]:
767
        return None             # *fmt will set the color
9 ✔
768
    elif colorspec != None:
9 ✔
769
        return colorspec
9 ✔
770

771
    # Figure out what color cycle to use, if not given by caller
772
    if color_cycle == None:
9 ✔
773
        color_cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']
9 ✔
774

775
    # Find the lines that we should pay attention to
776
    if lines is None and ax is not None:
9 ✔
777
        lines = ax.lines
9 ✔
778

779
    # If we were passed a set of lines, try to increment color from previous
780
    if offset is not None:
9 ✔
781
        return color_cycle[offset]
9 ✔
782
    elif lines is not None:
9 ✔
783
        color_offset = 0
9 ✔
784
        if len(ax.lines) > 0:
9 ✔
785
            last_color = ax.lines[-1].get_color()
9 ✔
786
            if last_color in color_cycle:
9 ✔
787
                color_offset = color_cycle.index(last_color) + 1
9 ✔
788
        color_offset = color_offset % len(color_cycle)
9 ✔
789
        return color_cycle[color_offset]
9 ✔
790
    else:
791
        return None
9 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc