Completed
Pull Request — master (#378)
by
unknown
01:29
created

delete_masked_points()   B

Complexity

Conditions 5

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
dl 0
loc 21
rs 8.439
c 1
b 0
f 0
1
# Copyright (c) 2008-2015 MetPy Developers.
2
# Distributed under the terms of the BSD 3-Clause License.
3
# SPDX-License-Identifier: BSD-3-Clause
4
"""Utilities for use in making plots."""
5
6
import functools
7
from matplotlib.collections import LineCollection
8
import numpy as np
9
10
from ..units import concatenate
11
12
13
# Not part of public API
14
def colored_line(x, y, c, **kwargs):
15
    """Create a multi-colored line.
16
17
    Takes a set of points and turns them into a collection of lines colored by another array.
18
19
    Parameters
20
    ----------
21
    x : array-like
22
        x-axis coordinates
23
    y : array-like
24
        y-axis coordinates
25
    c : array-like
26
        values used for color-mapping
27
    kwargs : dict
28
        Other keyword arguments passed to :class:`matplotlib.collections.LineCollection`
29
30
    Returns
31
    -------
32
        The created :class:`matplotlib.collections.LineCollection` instance.
33
34
    """
35
    # Mask out any NaN values
36
    nan_mask = ~(np.isnan(x) | np.isnan(y) | np.isnan(c))
37
    x = x[nan_mask]
38
    y = y[nan_mask]
39
    c = c[nan_mask]
40
41
    # Paste values end to end
42
    points = concatenate([x, y])
43
44
    # Exploit numpy's strides to present a view of these points without copying.
45
    # Dimensions are (segment, start/end, x/y). Since x and y are concatenated back to back,
46
    # moving between segments only moves one item; moving start to end is only an item;
47
    # The move between x any moves from one half of the array to the other
48
    num_pts = points.size // 2
49
    final_shape = (num_pts - 1, 2, 2)
50
    final_strides = (points.itemsize, points.itemsize, num_pts * points.itemsize)
51
    segments = np.lib.stride_tricks.as_strided(points, shape=final_shape,
52
                                               strides=final_strides)
53
54
    # Create a LineCollection from the segments and set it to colormap based on c
55
    lc = LineCollection(segments, **kwargs)
56
    lc.set_array(c)
57
    return lc
58
59
60
def delete_masked_points(*arrs):
61
    """ Delete masked points from arrays.
62
63
    Takes arrays and removes masked points to help with calculations and plotting.
64
65
    Parameters
66
    ----------
67
    arrs : array-like
68
        list of arrays
69
70
    Returns
71
    -------
72
    arrs : array-like
73
        list of arrays with masked elements removed
74
75
    """
76
    if any(hasattr(a, 'mask') for a in arrs):
77
        keep = ~functools.reduce(np.logical_or, (np.ma.getmaskarray(a) for a in arrs))
78
        return tuple(a[keep] for a in arrs)
79
    else:
80
        return arrs
81