Skip to content

pyplot

Wrapper for matplotlib plotting functions.

imshow(*args, ax=None, **kwargs)

Display an image, i.e. data on a 2D regular raster.

This is a wrapper of pyplot.imshow(). In contrast to the original function the default value of zorder is increased to 1.

Parameters:

Returns:

Source code in src/prettypyplot/pyplot.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def imshow(*args, ax: Axes | None = None, **kwargs) -> AxesImage:
    """Display an image, i.e. data on a 2D regular raster.

    This is a wrapper of pyplot.imshow(). In contrast to the original function
    the default value of `zorder` is increased to `1`.

    Parameters
    ----------
    ax : Axes, optional
        [matplotlib.axes.Axes][] to plot in.
    args, kwargs
        See [matplotlib.pyplot.imshow][].

    Returns
    -------
    im : AxesImage
        Reference to plotted image [matplotlib.image.AxesImage][]

    """
    args, ax = tools.parse_axes(*args, ax=ax)

    if 'zorder' not in kwargs:
        kwargs['zorder'] = 1

    # plot
    return ax.imshow(*args, **kwargs)

plot(*args, ax=None, **kwargs)

Plot simple lineplot.

Wrapping pyplot.plot() to adjust to style. For more information on the arguments see in matplotlib documentation. If STYLE='minimal', spines will be limited to plotting range.

Parameters:

Returns:

Source code in src/prettypyplot/pyplot.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def plot(*args, ax: Axes | None = None, **kwargs) -> list[Line2D]:
    """Plot simple lineplot.

    Wrapping pyplot.plot() to adjust to style. For more information on the
    arguments see in matplotlib documentation.
    If `STYLE='minimal'`, spines will be limited to plotting range.

    Parameters
    ----------
    ax : Axes
        [matplotlib.axes.Axes][] to plot in.
    args, kwargs
        See [matplotlib.pyplot.plot][].

    Returns
    -------
    lines : list of Line2D
        A list of [matplotlib.lines.Line2D][] representing the plotted data.

    """
    # parse axes
    args, ax = tools.parse_axes(*args, ax=ax)

    # plot
    lines = ax.plot(*args, **kwargs)

    if _pplt.STYLE == Style.MINIMAL:
        _set_spine_bounds(ax)

    return lines

savefig(fname, reference_ax=None, use_canvas_size=True, **kwargs)

Save the current figure.

Wrapper of pyplot.savefig() which first applies tight_layout. If use_canvas_size, the figure is resized such that reference_ax has the specified figsize and labels, ticks and legends are added around it. In poster and beamer mode the figure is enlarged by a factor of 3 before calculating the layout. The figsize is restored afterwards, so the figure can be saved multiple times.

Parameters:

  • fname (str or path - like) –

    Output filename. If no file ending, pdf will be used.

  • reference_ax (Axes, default: None ) –

    matplotlib.axes.Axes used for resizing. If None first axes of figure is used.

  • use_canvas_size (bool, default: True ) –

    If True the specified figsize will be used as canvas size.

  • kwargs –
Source code in src/prettypyplot/pyplot.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def savefig(
    fname: str | PathLike[str],
    reference_ax: Axes | None = None,
    use_canvas_size: bool = True,
    **kwargs,
) -> None:
    """Save the current figure.

    Wrapper of pyplot.savefig() which first applies `tight_layout`. If
    `use_canvas_size`, the figure is resized such that `reference_ax` has the
    specified figsize and labels, ticks and legends are added around it. In
    poster and beamer mode the figure is enlarged by a factor of 3 before
    calculating the layout. The figsize is restored afterwards, so the figure
    can be saved multiple times.

    Parameters
    ----------
    fname : str or path-like
        Output filename. If no file ending, pdf will be used.
    reference_ax : Axes, optional
        [matplotlib.axes.Axes][] used for resizing. If `None` first axes of
        figure is used.
    use_canvas_size : bool, optional
        If True the specified figsize will be used as canvas size.
    kwargs
        See [matplotlib.pyplot.savefig][].

    """
    set_figsize = _resize_canvas(
        reference_ax=reference_ax,
        use_canvas_size=use_canvas_size,
    )

    # save as pdf if not specified
    if 'format' not in kwargs:
        if path.splitext(fname)[1][1:] == '':
            fname = '{0}.pdf'.format(fname)

    # save fig
    plt.savefig(fname, **kwargs)

    # reset figsize, if user calls this function multiple times on same figure
    fig = plt.gcf()
    fig.set_size_inches(set_figsize)

show(reference_ax=None, use_canvas_size=True, **kwargs)

Show the current figure, resized like with savefig.

Parameters:

  • reference_ax (Axes, default: None ) –

    matplotlib.axes.Axes used for resizing. If None first axes of figure is used.

  • use_canvas_size (bool, default: True ) –

    If True the specified figsize will be used as canvas size.

  • kwargs –
Source code in src/prettypyplot/pyplot.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def show(
    reference_ax: Axes | None = None,
    use_canvas_size: bool = True,
    **kwargs,
) -> None:
    """Show the current figure, resized like with `savefig`.

    Parameters
    ----------
    reference_ax : Axes, optional
        [matplotlib.axes.Axes][] used for resizing. If `None` first axes of
        figure is used.
    use_canvas_size : bool, optional
        If True the specified figsize will be used as canvas size.
    kwargs
        See [matplotlib.pyplot.show][].

    """
    set_figsize = _resize_canvas(
        reference_ax=reference_ax,
        use_canvas_size=use_canvas_size,
    )

    # save fig
    plt.show(**kwargs)

    # reset figsize, if user calls this function multiple times on same figure
    fig = plt.gcf()
    fig.set_size_inches(set_figsize)

legend(*args, outside=False, ax=None, axs=None, deduplicate=True, **kwargs)

Generate a nice legend.

This is a wrapper of pyplot.legend(). Take a look there for the default arguments and options. The ticks and labels are moved to the opposite side. For top and bottom the default value of columns is set to the number of labels, for all other options to 1. In case of many labels this parameter needs to be adjusted.

When axs is provided without ax, the legend spans the full extent of all given axes. outside must be set to 'top', 'bottom', or 'right' in this case. For 'top' and 'bottom' the legend spans the full width (including the space between the axes); for 'right' it is vertically centred across all axes.

Note

Use handles and labels from *args if provided

Example

Checkout the gallery for an example.

Parameters:

  • outside (str or bool, default: False ) –

    False, 'top', 'right', 'bottom' or 'left'.

  • axs (list of Axes, default: None ) –

    List of matplotlib.axes.Axes which are used for extracting all labels. When provided without ax, outside must be 'top', 'bottom', or 'right' and the legend is placed at figure level spanning all axes.

  • ax (Axes, default: None ) –

    matplotlib.axes.Axes which is used for placing legend.

  • deduplicate (bool, default: True ) –

    If True (default), duplicate legend entries with the same label and visual appearance are removed. Set to False to keep all entries.

  • args –
  • kwargs –

Returns:

  • leg ( Legend ) –

    [matplotlib.legend.Legend] legend handle.

Source code in src/prettypyplot/pyplot.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
def legend(
    *args,
    outside: Literal[False, 'top', 'bottom', 'left', 'right'] = False,
    ax: Axes | None = None,
    axs: Sequence[Axes] | np.ndarray | None = None,
    deduplicate: bool = True,
    **kwargs,
) -> Legend:
    """Generate a nice legend.

    This is a wrapper of pyplot.legend(). Take a look there for the default
    arguments and options. The ticks and labels are moved to the opposite side.
    For `top` and `bottom` the default value of columns is set to the number of
    labels, for all other options to 1. In case of many labels this parameter
    needs to be adjusted.

    When `axs` is provided without `ax`, the legend spans the full extent of
    all given axes. `outside` must be set to `'top'`, `'bottom'`, or `'right'`
    in this case. For `'top'` and `'bottom'` the legend spans the full width
    (including the space between the axes); for `'right'` it is vertically
    centred across all axes.

    !!! note
        Use handles and labels from *args if provided

    !!! example
        Checkout the gallery for [an example](../../gallery/legend).

    Parameters
    ----------
    outside : str or bool
        False, 'top', 'right', 'bottom' or 'left'.
    axs : list of Axes
        List of [matplotlib.axes.Axes][] which are used for extracting all
        labels. When provided without `ax`, `outside` must be `'top'`,
        `'bottom'`, or `'right'` and the legend is placed at figure level
        spanning all axes.
    ax : Axes
        [matplotlib.axes.Axes][] which is used for placing legend.
    deduplicate : bool, optional
        If `True` (default), duplicate legend entries with the same label and
        visual appearance are removed. Set to `False` to keep all entries.
    args, kwargs
        See [matplotlib.pyplot.legend][].

    Returns
    -------
    leg : Legend
        [matplotlib.legend.Legend] legend handle.

    """
    default_kwargs = _legend_default_kwargs()
    if outside not in {False, *default_kwargs}:
        raise ValueError(
            'Use for outside one of [False, {0}]'.format(
                ', '.join(['"{0}"'.format(dr) for dr in default_kwargs]),
            ),
        )

    # resolve whether we are in "multi-axes spanning" mode
    axs_only = axs is not None and ax is None
    if axs_only and not outside:
        raise ValueError(
            'When using axs without ax, outside must be set to {0}'.format(
                ', '.join(['"{0}"'.format(dr) for dr in default_kwargs]),
            ),
        )

    # parse axes
    args, ax = tools.parse_axes(*args, ax=ax)

    # parse axs
    if axs is None:
        axs = [ax]
    else:
        axs = tools.get_axes(axs)

    # shift axis to opposite side.
    if outside:
        activate_axis(_opposite_side(outside))

    # set anchor, mode and location
    kwargs = {**default_kwargs.get(outside, {}), **kwargs}

    # get handles and labels of selected axes
    handles, labels = mlegend._get_legend_handles_labels(axs)

    # deduplicate by (label, handle visual key)
    if deduplicate:
        handles, labels = _legend_deduplicate(handles=handles, labels=labels)

    # set number of ncol to the number of items
    if outside in {'top', 'bottom'}:
        kwargs.setdefault('ncol', len(labels))

    if axs_only:
        leg = _legend_spanning(axs, handles, labels, *args, **kwargs)
    else:
        leg = ax.legend(handles, labels, *args, **kwargs)

    _legend_style_frame(leg, outside=outside)

    # shift title to the left if on top or bottom
    if outside in {'top', 'bottom'}:
        _shift_legend_title(leg)

    return leg

activate_axis(position, ax=None)

Shift the specified axis to the opposite side.

Parameters:

  • position (str or list of str) –

    Specify axis to flip, one of ['left', 'right', 'top', 'bottom'].

  • ax (Axes, default: None ) –

    matplotlib.axes.Axes axes to flip axis.

Source code in src/prettypyplot/pyplot.py
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
def activate_axis(
    position: Literal['top', 'bottom', 'left', 'right'] | Sequence[str],
    ax: Axes | None = None,
) -> None:
    """Shift the specified axis to the opposite side.

    Parameters
    ----------
    position : str or list of str
        Specify axis to flip, one of `['left', 'right', 'top', 'bottom']`.
    ax : Axes
        [matplotlib.axes.Axes][] axes to flip axis.

    """
    # get axes
    ax = tools.gca(ax)

    # convert string to list of strings
    if isinstance(position, str):
        position = [position]

    # allowed values
    positions = {'bottom', 'top', 'left', 'right'}

    # move axes ticks and labels to opposite side of position
    for pos in position:
        if pos not in positions:
            raise ValueError(
                '{0:!r} is not a valid value for {1}; supported values are {2}'.format(
                    pos, 'position', ', '.join(positions)
                )
            )

        if pos in {'bottom', 'top'}:
            axis = ax.xaxis
        elif pos in {'left', 'right'}:
            axis = ax.yaxis
        axis.set_ticks_position(pos)
        axis.set_label_position(pos)

colorbar(im, width='7%', pad='0%', position='right', label=None, **kwargs)

Generate colorbar of same height as image.

Wrapper around pyplot.colorbar which corrects the height.

Example

Checkout the gallery for an example.

Parameters:

  • im (ScalarMappable) –

    Specify the object the colorbar belongs to, e.g. the return value of matplotlib.pyplot.imshow or matplotlib.pyplot.pcolormesh.

  • width (str or float, default: '7%' ) –

    The width of the colorbar stated relative as string ending with '%' or absolute value in inches.

  • pad (str or float, default: '0%' ) –

    The width between figure and colorbar stated relative as string ending with '%' or absolute value in inches.

  • position (str, default: 'right' ) –

    Specify the position relative to the image where the colorbar is plotted, choose one of ['left', 'top', 'right', 'bottom']

  • label (str, default: None ) –

    Specify the colorbar label.

  • kwargs –

    Colorbar properties of, matplotlib.pyplot.colorbar.

Returns:

Source code in src/prettypyplot/pyplot.py
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
def colorbar(
    im: ScalarMappable,
    width: str | float = '7%',
    pad: str | float = '0%',
    position: Literal['top', 'bottom', 'left', 'right'] = 'right',
    label: str | None = None,
    **kwargs,
) -> Colorbar:
    """Generate colorbar of same height as image.

    Wrapper around pyplot.colorbar which corrects the height.

    !!! example
        Checkout the gallery for [an example](../../gallery/colorbar).

    Parameters
    ----------
    im : ScalarMappable
        Specify the object the colorbar belongs to, e.g. the return value of
        [matplotlib.pyplot.imshow][] or [matplotlib.pyplot.pcolormesh][].
    width : str or float, optional
        The width of the colorbar stated relative as string ending with '%' or
        absolute value in inches.
    pad : str or float, optional
        The width between figure and colorbar stated relative as string ending
        with '%' or absolute value in inches.
    position : str, optional
        Specify the position relative to the image where the colorbar is
        plotted, choose one of ['left', 'top', 'right', 'bottom']
    label : str, optional
        Specify the colorbar label.
    kwargs
        Colorbar properties of, [matplotlib.pyplot.colorbar][].

    Returns
    -------
    colorbar : Colorbar
        [matplotlib.colorbar.Colorbar][] instance.

    """
    orientation = 'vertical'
    if position in {'top', 'bottom'}:
        orientation = 'horizontal'

    # get axes
    if hasattr(im, 'axes'):
        ax = im.axes
    elif hasattr(im, 'ax'):
        ax = im.ax
    else:
        ax = plt.gca()

    # generate divider
    divider = mpl_axes_grid1.make_axes_locatable(ax)
    cax = divider.append_axes(position, width, pad=pad)

    cbar = plt.colorbar(im, cax=cax, orientation=orientation, **kwargs)
    if label:
        cbar.set_label(label)

    # set ticks and label of ticks to the outside
    activate_axis(position, ax=cax)
    # set the axis opposite to the colorbar to active
    activate_axis(_opposite_side(position), ax=ax)

    # invert width and pad
    pad_inv, width_inv = tools.invert_sign(pad), tools.invert_sign(width)
    cax_reset = divider.append_axes(position, width_inv, pad=pad_inv)
    cax_reset.set_visible(False)

    return cbar

grid(*args, ax=None, **kwargs)

Generate grid.

This function will add a major and minor grid in case of STYLE='default', a major grid in case of 'none' and otherwise nothing.

Parameters:

Source code in src/prettypyplot/pyplot.py
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
def grid(*args, ax: Axes | None = None, **kwargs):
    """Generate grid.

    This function will add a major and minor grid in case of STYLE='default',
    a major grid in case of 'none' and otherwise nothing.

    Parameters
    ----------
    ax : Axes
        [matplotlib.axes.Axes] axes to plot grid.
    args, kwargs
        See [matplotlib.pyplot.grid][].

    """
    # parse axes
    args, ax = tools.parse_axes(*args, ax=ax)

    if 'visible' in kwargs:  # mpl >= 3.6
        show_grid = kwargs['visible']
    elif 'b' in kwargs:  # mpl <=3.5
        show_grid = kwargs['b']
    else:
        boolargs = [arg for arg in args if isinstance(arg, bool)]
        show_grid = boolargs[0] if len(boolargs) >= 1 else True

    if _pplt.STYLE != Style.MINIMAL and show_grid:
        gr_maj = ax.grid(show_grid, which='major', linestyle='--', **kwargs)
        gr_min = ax.grid(show_grid, which='minor', linestyle='dotted', **kwargs)
    else:
        gr_maj = ax.grid(False, which='major')
        gr_min = ax.grid(False, which='minor')

    ax.set_axisbelow(True)
    return (gr_maj, gr_min)