Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions docs/iris/src/whatsnew/2.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,8 @@ Iris 2.2.0 Features
contiguous, or the cube's data must be masked at the discontiguities in
order to avoid plotting errors.

The iris plot functions :func:`iris.plot.quiver` and
:func:`iris.plot.streamplot` have been added, and these also work with
2-dimensional plot coordinates.
The iris plot functions :func:`iris.plot.quiver` has been added, and this
also works with 2-dimensional plot coordinates.

.. admonition:: 2-Dimensional Grid Vectors

Expand Down
55 changes: 4 additions & 51 deletions lib/iris/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1226,9 +1226,9 @@ def _vector_component_args(x_points, y_points, u_data, *args, **kwargs):
if crs:
if not isinstance(crs, (ccrs.PlateCarree, ccrs.RotatedPole)):
msg = ('Can only plot vectors provided in a lat-lon '
'projection, i.e. "cartopy.crs.PlateCarree" or '
'"cartopy.crs.RotatedPole". This '
"cubes coordinate system is {}.")
'projection, i.e. equivalent to "cartopy.crs.PlateCarree" '
'or "cartopy.crs.RotatedPole". This '
"cube coordinate system translates as Cartopy {}.")
raise ValueError(msg.format(crs))
# Given the above check, the Y points must be latitudes.
# We therefore **assume** they are in degrees : I'm not sure this
Expand All @@ -1237,7 +1237,7 @@ def _vector_component_args(x_points, y_points, u_data, *args, **kwargs):
# TODO: investigate degree units assumptions, here + elsewhere.

# Implement a latitude scaling, but preserve the given magnitudes.
v_data = v_data.copy()
u_data, v_data = [arr.copy() for arr in (u_data, v_data)]
mags = np.sqrt(u_data * u_data + v_data * v_data)
v_data *= np.cos(np.deg2rad(y_points))
scales = mags / np.sqrt(u_data * u_data + v_data * v_data)
Expand Down Expand Up @@ -1294,53 +1294,6 @@ def quiver(u_cube, v_cube, *args, **kwargs):
*args, **kwargs)


def streamplot(u_cube, v_cube, *args, **kwargs):
"""
Draws a streamline plot from two vector component cubes.

Args:

* u_cube, v_cube : (:class:`~iris.cube.Cube`)
u and v vector components. Must have same shape and units.
If the cubes have geographic coordinates, the values are treated as
true distance differentials, e.g. windspeeds, and *not* map coordinate
vectors. The components are aligned with the North and East of the
cube coordinate system.

.. Note:

At present, if u_cube and v_cube have geographic coordinates, then they
must be in a lat-lon coordinate system, though it may be a rotated one.
To transform wind values between coordinate systems, use
:func:`iris.analysis.cartography.rotate_vectors`.
To transform coordinate grid points, you will need to create
2-dimensional arrays of x and y values. These can be transformed with
:meth:`cartopy.crs.CRS.transform_points`.

Kwargs:

* coords: (list of :class:`~iris.coords.Coord` or string)
Coordinates or coordinate names. Use the given coordinates as the axes
for the plot. The order of the given coordinates indicates which axis
to use for each, where the first element is the horizontal
axis of the plot and the second element is the vertical axis
of the plot.

* axes: the :class:`matplotlib.axes.Axes` to use for drawing.
Defaults to the current axes if none provided.

See :func:`matplotlib.pyplot.quiver` for details of other valid
keyword arguments.

"""
#
# TODO: check u + v cubes for compatibility.
#
kwargs['_v_data'] = v_cube.data
return _draw_2d_from_points('streamplot', _vector_component_args, u_cube,
*args, **kwargs)


def plot(*args, **kwargs):
"""
Draws a line plot based on the given cube(s) or coordinate(s).
Expand Down
180 changes: 180 additions & 0 deletions lib/iris/tests/integration/plot/test_vector_plots.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
# (C) British Crown Copyright 2014 - 2016, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Test some key usages of :func:`iris.plot.quiver`.

"""

from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa

# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests

import numpy as np

import cartopy.crs as ccrs
from iris.coords import AuxCoord, DimCoord
from iris.coord_systems import Mercator
from iris.cube import Cube
from iris.tests.stock import sample_2d_latlons

# Run tests in no graphics mode if matplotlib is not available.
if tests.MPL_AVAILABLE:
import matplotlib.pyplot as plt
from iris.plot import quiver


@tests.skip_plot
class MixinVectorPlotCases(object):
"""
Test examples mixin, used by separate quiver + streamplot classes.

NOTE: at present for quiver only, as streamplot does not support arbitrary
coordinates.

"""

def plot(self, plotname, *args, **kwargs):
plot_function = self.plot_function_to_test()
plot_function(*args, **kwargs)
plt.suptitle(plotname)

@staticmethod
def _nonlatlon_xyuv():
# Create common x, y, u, v arrays for quiver/streamplot testing.
x = np.array([0., 2, 3, 5])
y = np.array([0., 2.5, 4])
uv = np.array([[(0., 0), (0, 1), (0, -1), (2, 1)],
[(-1, 0), (-1, -1), (-1, 1), (-2, 1)],
[(1., 0), (1, -1), (1, 1), (-2, 2)]])
uv = np.array(uv)
u, v = uv[..., 0], uv[..., 1]
return x, y, u, v

@staticmethod
def _nonlatlon_uv_cubes(x, y, u, v):
# Create u and v test cubes from x, y, u, v arrays.
coord_cls = DimCoord if x.ndim == 1 else AuxCoord
x_coord = coord_cls(x, long_name='x')
y_coord = coord_cls(y, long_name='y')
u_cube = Cube(u, long_name='u', units='ms-1')
if x.ndim == 1:
u_cube.add_dim_coord(y_coord, 0)
u_cube.add_dim_coord(x_coord, 1)
else:
u_cube.add_aux_coord(y_coord, (0, 1))
u_cube.add_aux_coord(x_coord, (0, 1))
v_cube = u_cube.copy()
v_cube.rename('v')
v_cube.data = v
return u_cube, v_cube

def test_non_latlon_1d_coords(self):
# Plot against simple 1D x and y coords.
x, y, u, v = self._nonlatlon_xyuv()
u_cube, v_cube = self._nonlatlon_uv_cubes(x, y, u, v)
self.plot('nonlatlon, 1-d coords', u_cube, v_cube)
plt.xlim(x.min() - 1, x.max() + 2)
plt.ylim(y.min() - 1, y.max() + 2)
self.check_graphic()

def test_non_latlon_2d_coords(self):
# Plot against expanded 2D x and y coords.
x, y, u, v = self._nonlatlon_xyuv()
x, y = np.meshgrid(x, y)
u_cube, v_cube = self._nonlatlon_uv_cubes(x, y, u, v)
# Call plot : N.B. default gives wrong coords order.
self.plot('nonlatlon_2d', u_cube, v_cube, coords=('x', 'y'))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The naming is inconsistent for the plot names as well, above it is 'nonlatlon, 1-d coords' but here it is 'nonlatlon_2d' but changing that would also mean changing the images in the other PR so I'm happy to leave it as they are.

Copy link
Member Author

@pp-mo pp-mo Sep 4, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually did this because otherwise the plots were too similar (just 1 title character different), and then they both got the same image hash value !

plt.xlim(x.min() - 1, x.max() + 2)
plt.ylim(y.min() - 1, y.max() + 2)
self.check_graphic()

@staticmethod
def _latlon_uv_cubes(grid_cube):
# Make a sample grid into u and v data for quiver/streamplot testing.
u_cube = grid_cube.copy()
u_cube.rename('dx')
u_cube.units = 'ms-1'
v_cube = u_cube.copy()
v_cube.rename('dy')
ny, nx = u_cube.shape
nn = nx * ny
angles = np.arange(nn).reshape((ny, nx))
angles = (angles * 360.0 / 5.5) % 360.
scale = np.arange(nn) % 5
scale = (scale + 4) / 4
scale = scale.reshape((ny, nx))
u_cube.data = scale * np.cos(np.deg2rad(angles))
v_cube.data = scale * np.sin(np.deg2rad(angles))
return u_cube, v_cube

def test_2d_plain_latlon(self):
# Test 2d vector plotting with implicit (PlateCarree) coord system.
u_cube, v_cube = self._latlon_uv_cubes(sample_2d_latlons())
ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=180))
self.plot('latlon_2d', u_cube, v_cube,
coords=('longitude', 'latitude'))
ax.coastlines(color='red')
ax.set_global()
self.check_graphic()

def test_2d_plain_latlon_on_polar_map(self):
# Test 2d vector plotting onto a different projection.
u_cube, v_cube = self._latlon_uv_cubes(sample_2d_latlons())
ax = plt.axes(projection=ccrs.NorthPolarStereo())
self.plot('latlon_2d_polar', u_cube, v_cube,
coords=('longitude', 'latitude'))
ax.coastlines(color='red')
self.check_graphic()

def test_2d_rotated_latlon(self):
# Test plotting vectors in a rotated latlon coord system.
u_cube, v_cube = self._latlon_uv_cubes(
sample_2d_latlons(rotated=True))
ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=180))
self.plot('2d_rotated', u_cube, v_cube,
coords=('longitude', 'latitude'))
ax.coastlines(color='red')
ax.set_global()
self.check_graphic()

def test_fail_unsupported_coord_system(self):
# Test plotting vectors in a rotated latlon coord system.
u_cube, v_cube = self._latlon_uv_cubes(sample_2d_latlons())
patch_coord_system = Mercator()
for cube in u_cube, v_cube:
for coord in cube.coords():
coord.coord_system = patch_coord_system
re_msg = ('Can only plot .* lat-lon projection, .* '
'This .* translates as Cartopy.*Mercator')
with self.assertRaisesRegexp(ValueError, re_msg):
self.plot('2d_rotated', u_cube, v_cube,
coords=('longitude', 'latitude'))


class TestQuiver(MixinVectorPlotCases, tests.GraphicsTest):
def setUp(self):
super(TestQuiver, self).setUp()

def plot_function_to_test(self):
return quiver


if __name__ == "__main__":
tests.main()
Loading