Skip to content

Commit

Permalink
ENH: Avoid formatting negative 0 (Fixes #3296)
Browse files Browse the repository at this point in the history
For modern Python, we can just use the 'z' format option. For earlier
Python versions, we need to manually round and add a positive 0 to the
result to clear the negative 0.
  • Loading branch information
dopplershift committed Nov 29, 2023
1 parent 8b5f911 commit b296d1f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/metpy/plots/station_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def plot_symbols(mapper, name, nwrap=10, figsize=(10, 1.4)):
kwargs['fontproperties'] = wx_symbol_font.copy()
return self.plot_parameter(location, codes, symbol_mapper, **kwargs)

def plot_parameter(self, location, parameter, formatter='.0f', **kwargs):
def plot_parameter(self, location, parameter, formatter=None, **kwargs):
"""At the specified location in the station model plot a set of values.
This specifies that at the offset `location`, the data in `parameter` should be
Expand All @@ -186,7 +186,7 @@ def plot_parameter(self, location, parameter, formatter='.0f', **kwargs):
formatter : str or Callable, optional
How to format the data as a string for plotting. If a string, it should be
compatible with the :func:`format` builtin. If a callable, this should take a
value and return a string. Defaults to '0.f'.
value and return a string. Defaults to 'z0.f'.
plot_units: `pint.unit`
Units to plot in (performing conversion if necessary). Defaults to given units.
kwargs
Expand Down Expand Up @@ -372,6 +372,14 @@ def _make_kwargs(self, kwargs):
@staticmethod
def _to_string_list(vals, fmt):
"""Convert a sequence of values to a list of strings."""
if fmt is None:
import sys
if sys.version_info >= (3, 11):
fmt = 'z.0f'
else:
def fmt(s):
"""Perform default formatting with no decimal places and no negative 0."""
return format(round(s, 0) + 0., '.0f')
if not callable(fmt):
def formatter(s):
"""Turn a format string into a callable."""
Expand Down
12 changes: 12 additions & 0 deletions tests/plots/test_station_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,18 @@ def test_station_plot_locations():
return fig


def test_station_plot_negative_zero():
"""Test that we avoid formatting a negative 0 by default."""
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
sp = StationPlot(ax, [0], [0])
text = sp.plot_parameter('C', [-0.04])

assert text.text[0] == '0'

plt.close(fig)


@pytest.mark.mpl_image_compare(tolerance=0.00413, savefig_kwargs={'dpi': 300},
remove_text=True)
def test_stationlayout_api():
Expand Down

0 comments on commit b296d1f

Please sign in to comment.