Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add check before plotting wind barbs #2788

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
14 changes: 12 additions & 2 deletions src/metpy/plots/declarative.py
Original file line number Diff line number Diff line change
Expand Up @@ -1660,9 +1660,19 @@ def _build(self):

wind_slice = (slice(None, None, self.skip[0]), slice(None, None, self.skip[1]))

# If too many of the winds/vectors to plot have excessively high magnitudes,
# the call to ax.barbs will cause matplotlib to draw so many pennants that all
# memory will be consumed, possibly hanging the system. Thus, here we check
# what we are about to plot to avoid the hang.
u_vals = u.values[wind_slice]
v_vals = v.values[wind_slice]
speeds = np.hypot(u_vals, v_vals)
if np.median(speeds) > 50000:
msg = "Too many large wind barbs to plot. Perhaps 'scale' is too high?"
raise ValueError(msg)

self.handle = self.parent.ax.barbs(
x_like[wind_slice], y_like[wind_slice],
u.values[wind_slice], v.values[wind_slice],
x_like[wind_slice], y_like[wind_slice], u_vals, v_vals,
color=self.color, pivot=self.pivot, length=self.barblength, zorder=2, **kwargs)


Expand Down
25 changes: 25 additions & 0 deletions tests/plots/test_declarative.py
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,31 @@ def test_no_field_error_barbs():
barbs.draw()


@needs_cartopy
def test_too_big_error_barbs():
"""Make sure we get an error when we are about to draw too many pennants."""
data = xr.open_dataset(get_test_data('narr_example.nc', as_file_obj=False)).squeeze()

Check warning

Code scanning / CodeQL

File is not always closed

File is opened but is not closed.

bp = BarbPlot()
bp.data = data
bp.field = ['u_wind', 'v_wind']
bp.level = 500
bp.scale = 1e4
bp.skip = [8, 8]

mp = MapPanel()
mp.layout = (1, 1, 1)
mp.area = (-100, -70, 30, 45)
mp.plots = [bp]

pc = PanelContainer()
pc.size = (10, 8)
pc.panels = [mp]

with pytest.raises(ValueError):
pc.draw()


@pytest.mark.mpl_image_compare(remove_text=True, tolerance=0.377)
def test_projection_object(ccrs, cfeature):
"""Test that we can pass a custom map projection."""
Expand Down