Completed
Pull Request — master (#413)
by
unknown
01:42
created

add_timestamp()   B

Complexity

Conditions 2

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 2
c 3
b 0
f 0
dl 0
loc 28
rs 8.8571
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
from datetime import datetime
7
import os
8
9
from matplotlib.collections import LineCollection
10
from matplotlib.pyplot import imread
11
import numpy as np
12
13
from ..units import concatenate
14
15
16
def add_timestamp(ax, time=None, x=0.99, y=-0.04, ha='right', **kwargs):
17
    r""" Add a timestamp at plot creation time.
18
19
    Adds an ISO format timestamp with the time of plot creation to the plot.
20
21
    Parameters
22
    ----------
23
    ax : `matplotlib.axes.Axes`
24
        The `Axes` instance used for plotting
25
    time : `datetime.datetime`
26
        Specific time to be plotted - datetime.utcnow will be use if not specified
27
    x : float
28
        Relative x position on the axes of the timestamp
29
    y : float
30
        Relative y position on the axes of the timestamp
31
    ha : str
32
        Horizontal alignment of the time stamp string
33
34
    Returns
35
    -------
36
    ax : `matplotlib.axes.Axes`
37
        The `Axes` instance used for plotting
38
    """
39
    if not time:
40
        time = datetime.utcnow()
41
    timestr = datetime.strftime(time, 'Created: %Y-%m-%dT%H:%M:%SZ')
42
    ax.text(x, y, timestr, ha=ha, transform=ax.transAxes, **kwargs)
43
    return ax
44
45
46
def add_logo(fig, x=10, y=25, zorder=100, size='small', **kwargs):
47
    r""" Add the MetPy logo to a figure.
48
49
        Adds an image of the MetPy logo to the figure.
50
51
        Parameters
52
        ----------
53
        fig : `matplotlib.figure`
54
            The `figure` instance used for plotting
55
        x : int
56
            x position padding in pixels
57
        y : float
58
            y position padding in pixels
59
        zorder : int
60
            The zorder of the logo
61
        size : str
62
            Size of logo to be used. Can be 'small' for 75 px square or 'large' for
63
            150 px square.
64
65
        Returns
66
        -------
67
        fig : `matplotlib.figure`
68
            The `figure` instance used for plotting
69
        """
70
    fnames = {'small': 'metpy_75x75.png',
71
              'large': 'metpy_150x150.png'}
72
    try:
73
        metpy_logo = imread(os.path.join(os.path.dirname(__file__), '_static', fnames[size]))
74
    except KeyError:
75
        raise ValueError('Unknown option for size: {0}'.format(str(size)))
76
77
    fig.figimage(metpy_logo, x, y, zorder=zorder, **kwargs)
78
    return fig
79
80
81
# Not part of public API
82
def colored_line(x, y, c, **kwargs):
83
    """Create a multi-colored line.
84
85
    Takes a set of points and turns them into a collection of lines colored by another array.
86
87
    Parameters
88
    ----------
89
    x : array-like
90
        x-axis coordinates
91
    y : array-like
92
        y-axis coordinates
93
    c : array-like
94
        values used for color-mapping
95
    kwargs : dict
96
        Other keyword arguments passed to :class:`matplotlib.collections.LineCollection`
97
98
    Returns
99
    -------
100
        The created :class:`matplotlib.collections.LineCollection` instance.
101
102
    """
103
    # Mask out any NaN values
104
    nan_mask = ~(np.isnan(x) | np.isnan(y) | np.isnan(c))
105
    x = x[nan_mask]
106
    y = y[nan_mask]
107
    c = c[nan_mask]
108
109
    # Paste values end to end
110
    points = concatenate([x, y])
111
112
    # Exploit numpy's strides to present a view of these points without copying.
113
    # Dimensions are (segment, start/end, x/y). Since x and y are concatenated back to back,
114
    # moving between segments only moves one item; moving start to end is only an item;
115
    # The move between x any moves from one half of the array to the other
116
    num_pts = points.size // 2
117
    final_shape = (num_pts - 1, 2, 2)
118
    final_strides = (points.itemsize, points.itemsize, num_pts * points.itemsize)
119
    segments = np.lib.stride_tricks.as_strided(points, shape=final_shape,
120
                                               strides=final_strides)
121
122
    # Create a LineCollection from the segments and set it to colormap based on c
123
    lc = LineCollection(segments, **kwargs)
124
    lc.set_array(c)
125
    return lc
126