Skip to content

prettypyplot

Prettypyplot

This package provides helper functions to easen the usage of matplotlib.

The module is structured into the following submodules:

  • pyplot: This submodule contains all methods related to plotting inside a single axes, so basically related to matplotlib.pyplot.

  • style: This module provides only method to load and alter the current style.

  • subplots: This module provides methods to simplify dealing with matplotlib.pyplot.subplots grids.

  • texts: This module provides methods to plot text with the possibility to add a contour.

  • tools: This module provides utility methods to.

categorical_cmap(nc, nsc, *, cmap=None, return_colors=False)

Generate categorical colors of given cmap.

Exract from a predefined colormap colors and generate for each the desired number of shades.

Parameters:

  • nc (int) –

    Number of colors

  • nsc (int) –

    Number of shades per colors

  • cmap (`matplotlib.colors.Colormap` or str, default: None ) –

    Matplotlib colormap to take colors from. The default is the active color cycle.

  • return_colors (bool, default: False ) –

    Return an array of rgb colors. Each color together with its shades are in an own row.

Returns:

  • scolors ( `matplotlib.colors.Colormap` or np.ndarray ) –

    Return discrete colormap. If return_colors, a 2d representation will be returned instead.

Source code in src/prettypyplot/colors.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def categorical_cmap(
    nc: int,
    nsc: int,
    *,
    cmap: str | Colormap | None = None,
    return_colors: bool = False,
) -> ListedColormap | np.ndarray:
    """Generate categorical colors of given cmap.

    Exract from a predefined colormap colors and generate for each the desired
    number of shades.

    Parameters
    ----------
    nc : int
        Number of colors
    nsc : int
        Number of shades per colors
    cmap : `matplotlib.colors.Colormap` or str, optional
        Matplotlib colormap to take colors from. The default is the active
        color cycle.
    return_colors : bool, optional
        Return an array of rgb colors. Each color together with its shades are
        in an own row.

    Returns
    -------
    scolors : `matplotlib.colors.Colormap` or np.ndarray
        Return discrete colormap. If return_colors, a 2d representation will
        be returned instead.

    """
    # check correct data type
    _is_number_in_range(
        nc,
        name='nc',
        dtype=int,
        low=1,
        high=np.iinfo(int).max,
    )
    _is_number_in_range(
        nsc,
        name='nsc',
        dtype=int,
        low=1,
        high=np.iinfo(int).max,
    )
    nc, nsc = int(nc), int(nsc)

    # get cmap
    if cmap is not None:
        cmap = plt.get_cmap(cmap)
    else:
        cmap = clr.ListedColormap(
            plt.rcParams['axes.prop_cycle'].by_key()['color'],
        )
    if nc > cmap.N:
        raise ValueError('Too many categories for colormap.')

    # extract colors from cmap
    if isinstance(cmap, clr.LinearSegmentedColormap):
        colors = cmap(np.linspace(0, 1, nc))
    elif isinstance(cmap, clr.ListedColormap):
        colors = cmap(np.arange(nc, dtype=int))

    # get shades of colors
    scolors = np.empty((nc, nsc, 3))
    for idx, color in enumerate(colors):
        scolors[idx] = categorical_color(nsc, color)

    if return_colors:
        return scolors
    return clr.ListedColormap(np.concatenate(scolors))

categorical_color(nsc, color, *, return_hex=False)

Generate categorical shades of given colors.

Generate for each provided color the number of specified shades. The shaded colors are interpolated linearly in HSV colorspace. This function is based on following post: https://stackoverflow.com/a/47232942

Parameters:

  • nsc (int) –

    Number of shades per color.

  • color (RGB color or matplotlib predefined color) –

    Color used for generating shades.

  • return_hex (bool, default: False ) –

    Return colors in hex format instead of rgb.

Returns:

  • colors_rgb ( list of RGB colors ) –

    A list containing shaded colors. Where the list is sorted from the original color at the beginning to the most shaded one at the end. The default color encoding is rgb and hex if specified.

Source code in src/prettypyplot/colors.py
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
def categorical_color(
    nsc: int,
    color: ColorType,
    *,
    return_hex: bool = False,
) -> np.ndarray | list[str]:
    """Generate categorical shades of given colors.

    Generate for each provided color the number of specified shades. The shaded
    colors are interpolated linearly in HSV colorspace. This function is based
    on following post: https://stackoverflow.com/a/47232942

    Parameters
    ----------
    nsc : int
        Number of shades per color.
    color : RGB color or matplotlib predefined color
        Color used for generating shades.
    return_hex : bool, optional
        Return colors in hex format instead of rgb.

    Returns
    -------
    colors_rgb : list of RGB colors
        A list containing shaded colors. Where the list is sorted from the
        original color at the beginning to the most shaded one at the end.
        The default color encoding is rgb and hex if specified.

    """
    # check correct data type
    color = clr.to_rgb(color)
    _is_number_in_range(
        nsc,
        name='nsc',
        dtype=int,
        low=1,
        high=np.iinfo(int).max,
    )
    nsc = int(nsc)

    # genrate shades of colors
    color_hsv = clr.rgb_to_hsv(color)
    colors_hsv = np.tile(color_hsv, nsc).reshape(nsc, 3)
    colors_hsv[:, 1] = np.linspace(color_hsv[1], 1 / 4, nsc)
    colors_hsv[:, 2] = np.linspace(color_hsv[2], 1, nsc)
    colors_rgb = clr.hsv_to_rgb(colors_hsv)

    # check if color is greyscale value, need to fix arbitrary hue value of 0
    if is_greyshade(color):
        colors_rgb[:, 0] = colors_rgb[:, 1]

    if return_hex:
        return [clr.to_hex(color) for color in colors_rgb]
    return colors_rgb

load_cmaps()

Load and include custom colormaps to matplotlib.

Add sequential colormaps pastel5, pastel6, cbf4, cbf5, cbf8, and ufcd as an corporate design. Except of ufcd all palettes should be 'color-blind-friendly'.

Add continuous colormaps macaw, Turbo. The Copyright of those are given on top of the data.

See

Choosing an cmaps.

Source code in src/prettypyplot/colors.py
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
147
148
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
178
def load_cmaps() -> None:
    """Load and include custom colormaps to matplotlib.

    Add sequential colormaps `pastel5`, `pastel6`, `cbf4`, `cbf5`, `cbf8`,
    and `ufcd` as an corporate design. Except of `ufcd` all palettes should be
    'color-blind-friendly'.

    Add continuous colormaps macaw, Turbo. The Copyright of those are given on
    top of the data.

    !!! see
        Choosing an [cmaps](../../gallery/cmaps).

    """
    colormaps = (
        _argon(),
        _pastel5(),
        _pastel6(),
        _cbf4(),
        _cbf5(),
        _cbf8(),
        _gdv_rag(),
        _gdv_rag_cvd(),
        _gdv_palette(),
        _gdv_6a(),
        _gdv_5a(),
        _gdv_4a(),
        _gdv_4b(),
        _gdv_3a(),
        _gdv_3b(),
        _gdv_2a(),
        _gdv_2b(),
        _gdv_s1(),
        _gdv_s2(),
        _gdv_s3(),
        _gdv_m1(),
        _gdv_m2(),
        _gdv_m3(),
        _gdv_d1(),
        _gdv_d2(),
        _gdv_d3(),
        _gdv_d4(),
        _gdv_mars(),
        _gdv_moon(),
        _pastel_autumn(),
        _pastel_rainbow(),
        _pastel_spring(),
        _paula(),
        _paula2(),
        _paula_cbf(),
        _paula_lime(),
        _summertimes(),
        _tol_bright(),
        _tol_high_contrast(),
        _tol_light(),
        _tol_medium_contrast(),
        _tol_muted(),
        _tol_vibrant(),
        _ufcd(),
        _turbo(),
        _macaw(),
        _bownair(),
    )
    # register own continuous and discrete cmaps
    for colormap in colormaps:
        # add cmap and reverse cmap
        for cmap in (colormap, colormap.reversed()):
            try:
                _get_cmap(cmap.name)
            except ValueError:
                _register_cmap(cmap=cmap)

load_colors()

Load and include custom colors to matplotlib.

Add colors of pastel5 which can be accessed via pplt:blue, pplt:red, pplt:green, pplt:orange, pplt:lightblue, pplt:gray and pplt:lightgray. Further, the current colors will be added pplt:axes, pplt:text, pplt:grid.

See

Choosing an cmaps.

Source code in src/prettypyplot/colors.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def load_colors() -> None:
    """Load and include custom colors to matplotlib.

    Add colors of `pastel5` which can be accessed via `pplt:blue`, `pplt:red`,
    `pplt:green`, `pplt:orange`, `pplt:lightblue`, `pplt:gray` and
    `pplt:lightgray`. Further, the current colors will be added `pplt:axes`,
    `pplt:text`, `pplt:grid`.

    !!! see
        Choosing an [cmaps](../../gallery/cmaps).

    """
    # register own colors
    pplt_colors = {
        'pplt:blue': _pastel5().colors[0],
        'pplt:red': _pastel5().colors[1],
        'pplt:green': _pastel5().colors[2],
        'pplt:orange': _pastel5().colors[3],
        'pplt:lightblue': _pastel5().colors[4],
        'pplt:gray': default_grays.dark,
        'pplt:grey': default_grays.dark,
        'pplt:lightgray': default_grays.light,
        'pplt:lightgrey': default_grays.light,
        'pplt:axes': plt.rcParams['axes.edgecolor'],
        'pplt:text': plt.rcParams['text.color'],
        'pplt:grid': plt.rcParams['grid.color'],
    }
    clr._colors_full_map.update(pplt_colors)

text_color(bgcolor, colors=('#000000', '#ffffff'))

Select textcolor with maximal contrast on background.

All parameters needs to be colors accepted by matplotlib, see matplotlib.colors. The formulas are taken from W3C WCAG 2.1 (Web Content Accessibility Guidelines).

Parameters:

  • bgcolor (matplotlib color) –

    Background color to which the contrast is maximized.

  • colors (list of matplotlib colors, default: ('#000000', '#ffffff') ) –

    Selection of textcolors to choose from.

Returns:

  • color ( matplotlib color ) –

    Color of colors which has the highest contrast on the given bgcolor.

Source code in src/prettypyplot/colors.py
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
def text_color(
    bgcolor: ColorType,
    colors: Sequence[ColorType] = ('#000000', '#ffffff'),
) -> ColorType:
    """Select textcolor with maximal contrast on background.

    All parameters needs to be colors accepted by matplotlib, see
    [matplotlib.colors](https://matplotlib.org/api/colors_api.html).
    The formulas are taken from W3C [WCAG 2.1](https://www.w3.org/TR/WCAG21)
    (Web Content Accessibility Guidelines).

    Parameters
    ----------
    bgcolor : matplotlib color
        Background color to which the contrast is maximized.
    colors : list of matplotlib colors, optional
        Selection of textcolors to choose from.

    Returns
    -------
    color : matplotlib color
        Color of colors which has the highest contrast on the given bgcolor.

    """
    # check input by casting to matplotlib colors
    bgcolor = clr.to_rgb(bgcolor)
    colors_rgb = [clr.to_rgb(color) for color in colors]

    # calculate the (luminances)
    bgL = _relative_luminance(bgcolor)
    Ls = [_relative_luminance(color) for color in colors_rgb]

    # calculate contrast between bgcolor and all colors
    contrast = [_contrast(bgL, Luminance) for Luminance in Ls]

    # return color corresponding to greatest contrast
    idx = contrast.index(max(contrast))
    return colors[idx]

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)

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)

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

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)

update_style(interactive=None, colors=None, cmap=None, ncs=None, figsize=None, figratio=None, mode=None, style=None, ipython=None, true_black=None, latex=None, sf=None)

Update alternative matplotlib style.

This function updates specified parameters of use_style without changing other.

Parameters:

  • interactive (bool, default: None ) –

    Set interactive mode.

  • colors (string, default: None ) –

    Set the default color cycler from continuous or discrete maps. Use any of matplotlibs defaults or specified in the colors submodule.

  • cmap (string, default: None ) –

    Set the default colormap.

  • ncs (int, default: None ) –

    Number of colors if continuous cmap is selected.

  • figsize (float or tuple of floats, default: None ) –

    Give size of default figure in inches, either as tuple (x, y) or a single float for the x-axis. The y-axis will be determined by figratio. When saving with savefig, this is the size of the axes.

  • figratio (str or float, default: None ) –

    Set ratio of figsize x:y to 1:1/'option', where 'option' is one of ['sqrt(2)', 'golden', 'sqrt(3)'] or any number. Golden stands for the golden ratio (1.618). This option is ignored if figsize is used with tuple.

  • mode (str, default: None ) –

    One of the following modes: 'default': use matplotlib defaults 'print': slightly larger fonts and lines 'beamer': extra large fontsize, for slides 'poster': for Din A0 posters

  • style (str, default: None ) –

    One of the following styles: 'default': enables grid and upper and right spines 'minimal': removes all unneeded lines 'none': no changes to style

  • ipython (bool, default: None ) –

    Deactivate high-res in jpg/png for compatibility with IPyhton, e.g. jupyter notebook/lab.

  • true_black (bool, default: None ) –

    If true black will be used for labels and co., else a dark grey.

  • latex (bool, default: None ) –

    If true LaTeX font will be used. This is only applied if a latex executable is found, so text rendering depends on the machine.

  • sf (bool, default: None ) –

    Use sans-serif font for text and latex math environment.

Source code in src/prettypyplot/style.py
 67
 68
 69
 70
 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
101
102
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
147
148
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def update_style(  # noqa: C901
    interactive: bool | None = None,
    colors: str | None = None,
    cmap: str | None = None,
    ncs: int | None = None,
    figsize: float | tuple[float] | tuple[float, float] | None = None,
    figratio: Literal['sqrt(2)', 'golden', 'sqrt(3)'] | float | None = None,
    mode: Literal['default', 'print', 'beamer', 'poster'] | Mode | None = None,
    style: Literal['default', 'minimal', 'none'] | Style | None = None,
    ipython: bool | None = None,
    true_black: bool | None = None,
    latex: bool | None = None,
    sf: bool | None = None,
) -> None:
    """Update alternative matplotlib style.

    This function updates specified parameters of `use_style` without changing
    other.

    Parameters
    ----------
    interactive : bool, optional
        Set interactive mode.
    colors : string, optional
        Set the default color cycler from continuous or discrete maps. Use any
        of matplotlibs defaults or specified in the colors submodule.
    cmap : string, optional
        Set the default colormap.
    ncs : int, optional
        Number of colors if continuous cmap is selected.
    figsize : float or tuple of floats, optional
        Give size of default figure in inches, either as tuple (x, y) or a
        single float for the x-axis. The y-axis will be determined by figratio.
        When saving with [savefig][prettypyplot.savefig], this is the size of
        the axes.
    figratio : str or float, optional
        Set ratio of figsize x:y to 1:1/'option', where 'option' is one
        of `['sqrt(2)', 'golden', 'sqrt(3)']` or any number. Golden stands for
        the golden ratio (1.618). This option is ignored if figsize is used
        with tuple.
    mode : str, optional
        One of the following modes:
        `'default'`: use matplotlib defaults
        `'print'`: slightly larger fonts and lines
        `'beamer'`: extra large fontsize, for slides
        `'poster'`: for Din A0 posters
    style : str, optional
        One of the following styles:
        `'default'`: enables grid and upper and right spines
        `'minimal'`: removes all unneeded lines
        `'none'`: no changes to style
    ipython : bool, optional
        Deactivate high-res in jpg/png for compatibility with IPyhton, e.g.
        jupyter notebook/lab.
    true_black : bool, optional
        If true black will be used for labels and co., else a dark grey.
    latex : bool, optional
        If true LaTeX font will be used. This is only applied if a `latex`
        executable is found, so text rendering depends on the machine.
    sf : bool, optional
        Use sans-serif font for text and latex math environment.

    """
    # set selected mode and style
    if style is not None:
        if isinstance(style, Style):
            pass
        elif isinstance(style, str) and style.upper() in Style.keys_list():
            style = Style[style.upper()]
        else:
            raise ValueError(
                'Style "{st}" is not supported, use one of {sts}.'.format(
                    st=style,
                    sts=Style.keys_list(),
                ),
            )
        _pplt.STYLE = style

    if mode is not None:
        if isinstance(mode, Mode):
            pass
        elif isinstance(mode, str) and mode.upper() in Mode.keys_list():
            mode = Mode[mode.upper()]
        else:
            raise ValueError(
                'Mode "{mode}" is not supported, use one of {modes}.'.format(
                    mode=mode,
                    modes=Mode.keys_list(),
                ),
            )

        _pplt.MODE = mode

    # set style variables in dictionary
    for key, val in (
        ('interactive', interactive),
        ('colors', colors),
        ('cmap', cmap),
        ('ncs', ncs),
        ('figsize', figsize),
        ('figratio', figratio),
        ('ipython', ipython),
        ('true_black', true_black),
        ('latex', latex),
        ('sf', sf),
    ):
        if val is not None:
            _pplt.STYLE_DICT[key] = val

    if _pplt.STYLE is Style.NONE:
        _reset_style()
    else:
        # load static rcParams
        _apply_style('stylelib/default.mplstyle')
        if _pplt.STYLE is Style.MINIMAL:
            _apply_style('stylelib/minimal.mplstyle')

        # set color cycle and cmap
        _set_rc_colors(
            colors=colors,
            cmap=cmap,
            ncs=ncs,
            true_black=true_black,
        )

        # set figsize
        if figsize is not None:
            _set_rc_figsize(figratio=figratio, figsize=figsize)

        # increase dpi if not in iypthon
        _set_rc_dpi(ipython)

        # set interactive mode
        _set_ineractive_mode(interactive=interactive)

        # setup LaTeX font if latex is available
        # plt.style.use can not be used.
        if latex and shutil.which('latex'):
            _apply_style('stylelib/latex.mplstyle')

        if sf:
            _set_rc_sansserif()

    if mode is not None:
        # change widths and fontsize depending on MODE
        _set_rc_widths(mode)

use_style(interactive=None, colors='pastel5', cmap='macaw', ncs=10, figsize=(3,), figratio='golden', mode='default', style='default', ipython=False, true_black=False, latex=True, sf=False)

Define alternative matplotlib style.

This function restores first the matplolib default values and finally changes depicted values to achieve a more appealing appearence. It additionally loads pplts colormaps and colors in matplolib.

See update_style for parameters.

Source code in src/prettypyplot/style.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
@copy_doc_params(update_style)
def use_style(
    interactive: bool | None = None,
    colors: str = 'pastel5',
    cmap: str = 'macaw',
    ncs: int = 10,
    figsize: float | tuple[float] | tuple[float, float] = (3,),
    figratio: Literal['sqrt(2)', 'golden', 'sqrt(3)'] | float = 'golden',
    mode: Literal['default', 'print', 'beamer', 'poster'] | Mode = 'default',
    style: Literal['default', 'minimal', 'none'] | Style = 'default',
    ipython: bool = False,
    true_black: bool = False,
    latex: bool = True,
    sf: bool = False,
) -> None:
    """Define alternative matplotlib style.

    This function restores first the matplolib default values and finally
    changes depicted values to achieve a more appealing appearence.
    It additionally loads pplts colormaps and colors in matplolib.

    See [update_style][prettypyplot.update_style] for parameters.

    """
    # restore matplotlib defaults
    _reset_style()

    # register own continuous and discrete cmaps
    pclr.load_cmaps()

    # update style
    update_style(
        interactive=interactive,
        colors=colors,
        cmap=cmap,
        ncs=ncs,
        figsize=figsize,
        figratio=figratio,
        mode=mode,
        style=style,
        ipython=ipython,
        true_black=true_black,
        latex=latex,
        sf=sf,
    )

    # register used colors
    pclr.load_colors()

add_contour(txt, contourwidth, contourcolor='w')

Draw contour around txt.

Parameters:

  • txt (mpl Text) –

    Instance of matplotlib.text.Text. Can be obtained by, e.g., txt = plt.text() or txt = plt.figtext().

  • contourwidth (scalar) –

    Width of contour.

  • contourcolor (RGB color or matplotlib predefined color, default: 'w' ) –

    Color of contour, default is white.

Source code in src/prettypyplot/texts.py
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def add_contour(
    txt: Text,
    contourwidth: float,
    contourcolor: ColorType = 'w',
) -> None:
    r"""Draw contour around txt.

    Parameters
    ----------
    txt : mpl Text
        Instance of [matplotlib.text.Text][]. Can be obtained by, e.g.,
        `txt = plt.text()` or `txt = plt.figtext()`.
    contourwidth : scalar
        Width of contour.
    contourcolor : RGB color or matplotlib predefined color, optional
        Color of contour, default is white.

    """
    # check if is text object
    if not isinstance(txt, mpl.text.Text):
        raise TypeError(
            'txt needs to be "matplotlib.text.Text", but ' + 'is {t}'.format(t=txt),
        )
    # check if number
    if not tools.is_number(contourwidth):
        raise TypeError(
            'contourwidth={w} needs to be a number.'.format(w=contourwidth),
        )

    # check if color
    if not clr.is_color_like(contourcolor):
        raise TypeError(
            'contourcolor={c} can not be '.format(c=contourcolor)
            + 'interpreted as color.',
        )

    path_args = [
        path_effects.withStroke(
            linewidth=contourwidth,
            foreground=contourcolor,
        )
    ]
    txt.set_path_effects(path_args)

figtext(x, y, s, *, contour=None, **kwargs)

Generate text object at figure position (x,y).

Wrapper around pyplot.figtext. The default alignment is changed to centered.

Parameters:

  • x (scalars) –

    The position to place the text in figure coordinates, so (0, 0) is the bottom left and (1, 1) the top right of the figure.

  • y (scalars) –

    The position to place the text in figure coordinates, so (0, 0) is the bottom left and (1, 1) the top right of the figure.

  • s (str) –

    The text.

  • contour (bool or tuple(scalar, color), default: None ) –

    Add a contour to the text. Either use a boolean for default values, or give a tuple with linewidth and linecolor.

  • kwargs –

    Text properties of matplotlib.pyplot.figtext

Source code in src/prettypyplot/texts.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def figtext(
    x: float,
    y: float,
    s: str,
    *,
    contour: bool | tuple[float, ColorType] | None = None,
    **kwargs,
) -> Text:
    """Generate text object at figure position (x,y).

    Wrapper around pyplot.figtext. The default alignment is changed to
    centered.

    Parameters
    ----------
    x, y : scalars
        The position to place the text in figure coordinates, so (0, 0) is
        the bottom left and (1, 1) the top right of the figure.
    s : str
        The text.
    contour : bool or tuple(scalar, color)
        Add a contour to the text. Either use a boolean for default values,
        or give a tuple with linewidth and linecolor.
    kwargs
        Text properties of [matplotlib.pyplot.figtext][]

    """
    # change default alignment
    if 'va' not in kwargs and 'verticalalignment' not in kwargs:
        kwargs['va'] = 'center'
    if 'ha' not in kwargs and 'horizontalalignment' not in kwargs:
        kwargs['ha'] = 'center'

    # plot text
    txt = plt.figtext(x=x, y=y, s=s, **kwargs)

    # generate contour
    if contour is not None:
        contour_kwargs = _parse_contour(contour)
        if contour_kwargs is not None:
            add_contour(txt, **contour_kwargs)

    return txt

text(x, y, s, *, contour=None, ax=None, **kwargs)

Generate text object at (x,y).

Wrapper around pyplot.text. The default alignment is changed to centered.

Parameters:

  • x (scalars) –

    The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.

  • y (scalars) –

    The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.

  • s (str) –

    The text.

  • contour (bool or tuple(scalar, color), default: None ) –

    Add a contour to the text. Either use a boolean for default values, or give a tuple with linewidth and linecolor.

  • ax (matplotlib axes, default: None ) –

    Matplotlib axes to plot in.

  • kwargs –

    Text properties of matplotlib.pyplot.text

Source code in src/prettypyplot/texts.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
69
70
71
72
73
74
def text(
    x: float,
    y: float,
    s: str,
    *,
    contour: bool | tuple[float, ColorType] | None = None,
    ax: Axes | None = None,
    **kwargs,
) -> Text:
    """Generate text object at (x,y).

    Wrapper around pyplot.text. The default alignment is changed to centered.

    Parameters
    ----------
    x, y : scalars
        The position to place the text. By default, this is in data
        coordinates. The coordinate system can be changed using the
        *transform* parameter.
    s : str
        The text.
    contour : bool or tuple(scalar, color)
        Add a contour to the text. Either use a boolean for default values,
        or give a tuple with linewidth and linecolor.
    ax : matplotlib axes
        Matplotlib axes to plot in.
    kwargs
        Text properties of [matplotlib.pyplot.text][]

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

    # change default alignment
    if 'va' not in kwargs and 'verticalalignment' not in kwargs:
        kwargs['va'] = 'center'
    if 'ha' not in kwargs and 'horizontalalignment' not in kwargs:
        kwargs['ha'] = 'center'

    # plot text
    txt = ax.text(x=x, y=y, s=s, **kwargs)

    # generate contour
    if contour is not None:
        contour_kwargs = _parse_contour(contour)
        if contour_kwargs is not None:
            add_contour(txt, **contour_kwargs)

    return txt

hide_empty_axes(axs=None)

Hide empty axes.

Loop over all axes and hide empty ones.

Parameters:

  • axs (mpl.axes.Axes or list of, default: None ) –

    Specify matplotlib.axes.Axes to check for empty state. Default use all of current figure.

Source code in src/prettypyplot/subplots.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def hide_empty_axes(axs: Axes | Sequence[Axes] | np.ndarray | None = None) -> None:
    """Hide empty axes.

    Loop over all axes and hide empty ones.

    Parameters
    ----------
    axs : mpl.axes.Axes or list of
        Specify [matplotlib.axes.Axes][] to check for empty state. Default use
        all of current figure.

    """
    # check for single axes
    axs = tools.get_axes(axs)

    # loop over all axes and hide empty ones
    for ax in axs:
        if _is_empty_axes(ax):
            ax.axis('off')

    # in case of shared axes, activate outer tick labels
    _activate_outer_ticks(axs)

label_outer(axs=None)

Only show outer labels and tick labels.

This checks for outest visible axes only. Works only with single Gridspec.

Parameters:

  • axs (mpl.axes.AxesSubplot or list of, default: None ) –

    Specify matplotlib.axes.Axes to check for labeling only outer. Default use all of current figure.

Source code in src/prettypyplot/subplots.py
60
61
62
63
64
65
66
67
68
69
70
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
def label_outer(axs: Axes | Sequence[Axes] | np.ndarray | None = None) -> None:
    """Only show outer labels and tick labels.

    This checks for outest visible axes only. Works only with single Gridspec.

    Parameters
    ----------
    axs : mpl.axes.AxesSubplot or list of
        Specify [matplotlib.axes.Axes][] to check for labeling only outer.
        Default use all of current figure.

    """
    # check for single axes
    if axs is not None:
        axs = tools.get_axes(axs)
        if not all((_is_subplot_axes(arg) for arg in axs)):
            raise TypeError(
                'axs needs to be of type matplotlib.axes.AxesSuplot.',
            )
    else:
        axs = [ax for ax in plt.gcf().get_axes() if _is_subplot_axes(ax)]

    for ax in axs:
        ss = ax.get_subplotspec()
        if hasattr(ss, 'is_last_row'):  # pragma: no cover # noqa: WPS421
            # for mpl >= 3.4
            lastrow = ss.is_last_row()
            firstcol = ss.is_first_col()
        elif hasattr(ax, 'is_last_row'):  # pragma: no cover # noqa: WPS421
            lastrow = ax.is_last_row()
            firstcol = ax.is_first_col()
        else:
            raise TypeError(f'{ax!r} is not a valid axes.')

        # check if axes below, left is hidden
        left_empty, bottom_empty = _is_outer_hidden(axs, ax)
        _label_outer(ax, lastrow or bottom_empty, firstcol or left_empty)

subplot_labels(*, fig=None, xlabel=None, ylabel=None)

Add global labels for subplots.

This method adds shared x- and y-labels for a grid of subplots. These can be created by, e.g. fig, axs = plt.subplots(...).

Parameters:

  • fig (matplotlib figure, default: None ) –

    If None the current figure will be used instead.

  • xlabel (str, default: None ) –

    String of x label.

  • ylabel (str, default: None ) –

    String of y label.

Source code in src/prettypyplot/subplots.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def subplot_labels(
    *,
    fig: Figure | None = None,
    xlabel: str | None = None,
    ylabel: str | None = None,
) -> None:
    """Add global labels for subplots.

    This method adds shared x- and y-labels for a grid of subplots. These can
    be created by, e.g. `fig, axs = plt.subplots(...)`.

    Parameters
    ----------
    fig : matplotlib figure, optional
        If `None` the current figure will be used instead.
    xlabel : str, optional
        String of x label.
    ylabel : str, optional
        String of y label.

    """
    # if no label passed, nothing to do
    if xlabel is None and ylabel is None:
        return

    # get active axes to restore it later on
    ca = plt.gca()

    if fig is None:
        fig = plt.gcf()

    _subplot_labels(fig, xlabel, ylabel)

    # reset current axes
    plt.sca(ca)