Skip to content

Commit 77ee0e6

Browse files
authored
Merge pull request #111 from csiro-coasts/bug/105-no-long-name
Fix error when plotting variables with no long_name
2 parents b72107c + d630515 commit 77ee0e6

File tree

4 files changed

+77
-3
lines changed

4 files changed

+77
-3
lines changed

docs/releases/development.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,5 @@ Next release (in development)
3131
This feature is considered experimental
3232
and may change significantly in future releases.
3333
(:pr:`110`).
34+
* Fix an issue with plotting variables with no ``long_name`` attribute.
35+
(:issue:`105`, :pr:`111`).

src/emsarray/conventions/_base.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -938,7 +938,10 @@ def plot_on_figure(
938938
#
939939
# Users can supply their own titles
940940
# if this automatic behaviour is insufficient
941-
kwargs['title'] = kwargs['scalar'].attrs.get('long_name')
941+
title_bits: list[str] = []
942+
long_name = kwargs['scalar'].attrs.get('long_name')
943+
if long_name is not None:
944+
title_bits.append(str(long_name))
942945
try:
943946
time_coordinate = self.dataset.variables[self.get_time_name()]
944947
except KeyError:
@@ -949,8 +952,11 @@ def plot_on_figure(
949952
# as long as the time coordinate is a proper coordinate with
950953
# matching dimension name, not an auxiliary coordinate.
951954
if time_coordinate.size == 1:
952-
time = time_coordinate.values
953-
kwargs['title'] = kwargs['title'] + '\n' + str(time)
955+
time = time_coordinate.values[0]
956+
title_bits.append(str(time))
957+
958+
if title_bits:
959+
kwargs['title'] = '\n'.join(title_bits)
954960

955961
plot_on_figure(figure, self, **kwargs)
956962

tests/conftest.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
import logging
12
import pathlib
23
from unittest import mock
34

45
import pytest
56

67
import emsarray
78

9+
logger = logging.getLogger(__name__)
10+
811

912
@pytest.fixture
1013
def datasets() -> pathlib.Path:
@@ -19,6 +22,7 @@ def pytest_runtest_setup(item):
1922

2023
@pytest.fixture
2124
def matplotlib_backend(
25+
request: pytest.FixtureRequest,
2226
monkeypatch: pytest.MonkeyPatch,
2327
backend: str = 'template',
2428
):
@@ -28,6 +32,12 @@ def matplotlib_backend(
2832
import matplotlib
2933
import matplotlib.pyplot
3034

35+
node = request.node
36+
mark = node.get_closest_marker('matplotlib')
37+
38+
if mark.kwargs.get('mock_coast', False):
39+
monkeypatch.setattr(emsarray.plot, 'add_coast', lambda figure: None)
40+
3141
show_mock = mock.Mock(spec=matplotlib.pyplot.show)
3242
monkeypatch.setattr(matplotlib.pyplot, 'show', show_mock)
3343

tests/test_plot.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
1+
import logging
2+
import pathlib
3+
14
import cartopy.crs
25
import matplotlib.figure
6+
import matplotlib.pyplot
37
import numpy
48
import pytest
59
import shapely
610

11+
import emsarray
712
from emsarray.plot import add_landmarks, polygons_to_collection
813

14+
logger = logging.getLogger(__name__)
15+
916

1017
@pytest.mark.matplotlib
1118
def test_polygons_to_collection():
@@ -43,3 +50,52 @@ def test_add_landmarks():
4350
for landmark, text in zip(landmarks, axes.texts):
4451
assert text.get_text() == landmark[0]
4552
assert text.xy == landmark[1].coords.xy
53+
54+
55+
@pytest.mark.matplotlib(mock_coast=True)
56+
@pytest.mark.tutorial
57+
def test_plot(
58+
datasets: pathlib.Path,
59+
tmp_path: pathlib.Path,
60+
):
61+
"""
62+
Test plotting a variable with no long_name attribute works.
63+
Regression test for https://github.com/csiro-coasts/emsarray/issues/105
64+
"""
65+
dataset = emsarray.tutorial.open_dataset('gbr4')
66+
temp = dataset['temp'].copy()
67+
temp = temp.isel(time=0, k=-1)
68+
69+
dataset.ems.plot(temp)
70+
71+
figure = matplotlib.pyplot.gcf()
72+
axes = figure.axes[0]
73+
assert axes.get_title() == 'Temperature\n2022-05-11T14:00:00.000000000'
74+
75+
matplotlib.pyplot.savefig(tmp_path / 'plot.png')
76+
logger.info("Saved plot to %r", tmp_path / 'plot.png')
77+
78+
79+
@pytest.mark.matplotlib(mock_coast=True)
80+
@pytest.mark.tutorial
81+
def test_plot_no_long_name(
82+
datasets: pathlib.Path,
83+
tmp_path: pathlib.Path,
84+
):
85+
"""
86+
Test plotting a variable with no long_name attribute works.
87+
Regression test for https://github.com/csiro-coasts/emsarray/issues/105
88+
"""
89+
dataset = emsarray.tutorial.open_dataset('gbr4')
90+
temp = dataset['temp'].copy()
91+
temp = temp.isel(time=0, k=-1)
92+
del temp.attrs['long_name']
93+
94+
dataset.ems.plot(temp)
95+
96+
figure = matplotlib.pyplot.gcf()
97+
axes = figure.axes[0]
98+
assert axes.get_title() == '2022-05-11T14:00:00.000000000'
99+
100+
matplotlib.pyplot.savefig(tmp_path / 'plot.png')
101+
logger.info("Saved plot to %r", tmp_path / 'plot.png')

0 commit comments

Comments
 (0)