Skip to content

Commit

Permalink
Merge pull request Unidata#927 from jrleeman/county_features
Browse files Browse the repository at this point in the history
Add US County features
  • Loading branch information
dopplershift authored Aug 27, 2018
2 parents cac1b2e + 83d1ed8 commit f47ebee
Show file tree
Hide file tree
Showing 15 changed files with 131 additions and 4 deletions.
26 changes: 26 additions & 0 deletions examples/plots/US_Counties.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Copyright (c) 2018 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""
US Counties
===========
Demonstrate how to plot US counties at all three available resolutions.
"""
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

from metpy.plots import USCOUNTIES

###########################################

proj = ccrs.LambertConformal(central_longitude=-85.0, central_latitude=45.0)

fig = plt.figure(figsize=(12, 9))
ax1 = fig.add_subplot(1, 3, 1, projection=proj)
ax2 = fig.add_subplot(1, 3, 2, projection=proj)
ax3 = fig.add_subplot(1, 3, 3, projection=proj)

for scale, axis in zip(['20m', '5m', '500k'], [ax1, ax2, ax3]):
axis.set_extent([270.25, 270.9, 38.15, 38.75], ccrs.Geodetic())
axis.add_feature(USCOUNTIES.with_scale(scale), edgecolor='black')
2 changes: 1 addition & 1 deletion metpy/calc/cross_sections.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
is based around xarray DataArrays.
"""

import cartopy.crs as ccrs
import numpy as np
import xarray as xr

Expand Down Expand Up @@ -85,6 +84,7 @@ def latitude_from_cross_section(cross):
if CFConventionHandler.check_axis(y, 'lat'):
return y
else:
import cartopy.crs as ccrs
latitude = ccrs.Geodetic().transform_points(cross.metpy.cartopy_crs,
cross.metpy.x.values,
y.values)[..., 1]
Expand Down
2 changes: 1 addition & 1 deletion metpy/interpolate/slices.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
# SPDX-License-Identifier: BSD-3-Clause
"""Tools for interpolating to a vertical slice/cross section through data."""

import cartopy.crs as ccrs
import numpy as np
import xarray as xr

Expand Down Expand Up @@ -81,6 +80,7 @@ def geodesic(crs, start, end, steps):
cross_section
"""
import cartopy.crs as ccrs
from pyproj import Geod

# Geod.npts only gives points *in between* the start and end, and we want to include
Expand Down
13 changes: 11 additions & 2 deletions metpy/plots/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# SPDX-License-Identifier: BSD-3-Clause
r"""Contains functionality for making meteorological plots."""

import logging

# Trigger matplotlib wrappers
from . import _mpl # noqa: F401
from ._util import add_metpy_logo, add_timestamp, add_unidata_logo, convert_gempak_color
Expand All @@ -11,9 +13,16 @@
from .station_plot import * # noqa: F403
from .wx_symbols import * # noqa: F403

logger = logging.getLogger(__name__)

__all__ = ctables.__all__[:] # pylint: disable=undefined-variable
__all__.extend(skewt.__all__) # pylint: disable=undefined-variable
__all__.extend(station_plot.__all__) # pylint: disable=undefined-variable
__all__.extend(wx_symbols.__all__) # pylint: disable=undefined-variable
__all__.extend([add_metpy_logo, add_timestamp, convert_gempak_color,
add_unidata_logo]) # pylint: disable=undefined-variable
__all__.extend([add_metpy_logo, add_timestamp, add_unidata_logo,
convert_gempak_color]) # pylint: disable=undefined-variable
try:
from .cartopy_utils import USCOUNTIES
__all__.extend([USCOUNTIES])
except ImportError:
logger.warning('Cannot import USCOUNTIES without cartopy installed.')
43 changes: 43 additions & 0 deletions metpy/plots/cartopy_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Copyright (c) 2018 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Cartopy specific mapping utilities."""

import cartopy.feature as cfeat
import cartopy.io.shapereader as shpreader

from ..cbook import get_test_data


class USCountiesFeature(cfeat.NaturalEarthFeature):
"""A simple interface to US County shapefiles."""

def __init__(self, scale, **kwargs):
"""Create USCountiesFeature instance."""
super(USCountiesFeature, self).__init__('', 'us_counties', scale, **kwargs)

def geometries(self):
"""Return an iterator of (shapely) geometries for this feature."""
# Ensure that the associated files are in the cache
fname = 'us_counties_{}'.format(self.scale)
for extension in ['.dbf', '.shx']:
get_test_data(fname + extension)
path = get_test_data(fname + '.shp', as_file_obj=False)
return iter(tuple(shpreader.Reader(path).geometries()))

def with_scale(self, new_scale):
"""
Return a copy of the feature with a new scale.
Parameters
----------
new_scale
The new dataset scale, i.e. one of '500k', '5m', or '20m'.
Corresponding to 1:500,000, 1:5,000,000, and 1:20,000,000
respectively.
"""
return USCountiesFeature(new_scale, **self.kwargs)


USCOUNTIES = USCountiesFeature('20m', facecolor='None')
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
43 changes: 43 additions & 0 deletions metpy/plots/tests/test_cartopy_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Copyright (c) 2018 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Test the cartopy utilities."""

import cartopy.crs as ccrs
import matplotlib
import matplotlib.pyplot as plt
import pytest

from metpy.plots import USCOUNTIES
# Fixtures to make sure we have the right backend and consistent round
from metpy.testing import patch_round, set_agg_backend # noqa: F401, I202

MPL_VERSION = matplotlib.__version__[:3]


@pytest.mark.mpl_image_compare(tolerance=0.053, remove_text=True)
def test_us_county_defaults():
"""Test the default US county plotting."""
proj = ccrs.LambertConformal(central_longitude=-85.0, central_latitude=45.0)

fig = plt.figure(figsize=(12, 9))
ax = fig.add_subplot(1, 1, 1, projection=proj)
ax.set_extent([270.25, 270.9, 38.15, 38.75], ccrs.Geodetic())
ax.add_feature(USCOUNTIES, edgecolor='black')
return fig


@pytest.mark.mpl_image_compare(tolerance=0.092, remove_text=True)
def test_us_county_scales():
"""Test US county plotting with all scales."""
proj = ccrs.LambertConformal(central_longitude=-85.0, central_latitude=45.0)

fig = plt.figure(figsize=(12, 9))
ax1 = fig.add_subplot(1, 3, 1, projection=proj)
ax2 = fig.add_subplot(1, 3, 2, projection=proj)
ax3 = fig.add_subplot(1, 3, 3, projection=proj)

for scale, axis in zip(['20m', '5m', '500k'], [ax1, ax2, ax3]):
axis.set_extent([270.25, 270.9, 38.15, 38.75], ccrs.Geodetic())
axis.add_feature(USCOUNTIES.with_scale(scale), edgecolor='black')
return fig
6 changes: 6 additions & 0 deletions metpy/static-data-manifest.txt
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,13 @@ nov11_sounding.txt 6fa3e0920314a7d55d6e1020eb934e18d9623c5fb1a40aaad546a25ed225e
rbf_test.npz f035f4415ea9bf04dcaf8affd7748f6519638655dcce90dad2b54fe0032bf32d
station_data.txt 3c1b71abb95ef8fe4adf57e47e2ce67f3529c6fe025b546dd40c862999fc5ffe
timeseries.csv 2d79f8f21ad1fcec12d0e24750d0958631e92c9148adfbd1b7dc8defe8c56fc5
us_counties_20m.dbf b5eeaa4769f25324d52933a6067e9a90315a77fefcdbefd0c7d99e94fd0cbb41
us_counties_20m.shp 8acb8bfbcf670028f7ce6c1c11ae08b21844b1c882c26ef397df33231831dee9
us_counties_20m.shx 131ccb63c365415c81c4fcd686b2bcbb9166e3a3d1fe97c1a5fc28344036a4ae
us_counties_500k.dbf 8cb3e42c3d951cf5b15e395bee61eb1ad50c0470bd0937e7288526605bf1ab85
us_counties_500k.shp 06463cf329d6f412d7f3323748225aca1ca495a8c04af58cfaf169fc3a8c8df4
us_counties_500k.shx aa301ee507e17bcd84a0792648eaea17a5efd7b274d14689a285603c0a61a8ba
us_counties_5m.dbf f7e5b7cb1da1a306652b4ca94212a91b4e08006691366ede1bca57c1b31018a4
us_counties_5m.shp be255ca37625e5feef7808ef996e803c6412ee67e52c29ee0b603b569eba083c
us_counties_5m.shx 7412c519095b9d2c3d3bf0e681f784f2b44fb4b4b6ce58d5b60fcd740dab2895
wrf_example.nc dcc1444db327507730334fd94dcb223025f77791448dd394f3ba06391ddbf98f
Binary file added staticdata/us_counties_20m.dbf
Binary file not shown.
Binary file added staticdata/us_counties_20m.shx
Binary file not shown.
Binary file added staticdata/us_counties_500k.dbf
Binary file not shown.
Binary file added staticdata/us_counties_500k.shx
Binary file not shown.
Binary file added staticdata/us_counties_5m.dbf
Binary file not shown.
Binary file added staticdata/us_counties_5m.shx
Binary file not shown.

0 comments on commit f47ebee

Please sign in to comment.