Completed
Push — master ( 1f8181...37354f )
by Ryan
23s
created

add_timestamp()   B

Complexity

Conditions 2

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

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