Skip to content

Commit 43d812d

Browse files
committed
ENH: Add the space_sep option to EngFormatter, and docstring updates
1 parent e8d4502 commit 43d812d

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

lib/matplotlib/ticker.py

+28-5
Original file line numberDiff line numberDiff line change
@@ -1190,6 +1190,9 @@ class EngFormatter(Formatter):
11901190
`places` is the precision with which to display the number,
11911191
specified in digits after the decimal point (there will be between
11921192
one and three digits before the decimal point).
1193+
1194+
`space_sep` controls if there is a space between the number and the
1195+
prefix/unit. For example, '3.14 mV' if True and '3.14mV' if False.
11931196
"""
11941197
# The SI engineering prefixes
11951198
ENG_PREFIXES = {
@@ -1212,9 +1215,27 @@ class EngFormatter(Formatter):
12121215
24: "Y"
12131216
}
12141217

1215-
def __init__(self, unit="", places=None):
1218+
def __init__(self, unit="", places=None, space_sep=True):
1219+
""" Parameters
1220+
----------
1221+
unit: str (default: u"")
1222+
Unit symbol to use.
1223+
1224+
places: int (default: None)
1225+
Precision, i.e. number of digits after the decimal point.
1226+
If it is None, falls back to the floating point format '%g'.
1227+
1228+
space_sep: boolean (default: True)
1229+
If True, a (single) space is used between the value and the
1230+
prefix/unit, else the prefix/unit is directly appended to the
1231+
value.
1232+
"""
12161233
self.unit = unit
12171234
self.places = places
1235+
if space_sep is True:
1236+
self.sep = u" " # 1 space
1237+
else:
1238+
self.sep = u"" # no space
12181239

12191240
def __call__(self, x, pos=None):
12201241
s = "%s%s" % (self.format_eng(x), self.unit)
@@ -1258,18 +1279,20 @@ def format_eng(self, num):
12581279

12591280
mant = sign * dnum / (10 ** pow10)
12601281

1282+
# TODO: shouldn't we raise a warning if self.places < 0?
12611283
if self.places is None:
1262-
format_str = "%g %s"
1284+
format_str = "%g{sep:s}%s".format(sep=self.sep)
12631285
elif self.places == 0:
1264-
format_str = "%i %s"
1286+
format_str = "%d{sep:s}%s".format(sep=self.sep)
12651287
elif self.places > 0:
1266-
format_str = ("%%.%if %%s" % self.places)
1288+
format_str = "%.{p:d}f{sep:s}%s".format(p=self.places,
1289+
sep=self.sep)
12671290

12681291
formatted = format_str % (mant, prefix)
12691292

12701293
formatted = formatted.strip()
12711294
if (self.unit != "") and (prefix == self.ENG_PREFIXES[0]):
1272-
formatted = formatted + " "
1295+
formatted = formatted + self.sep
12731296

12741297
return formatted
12751298

0 commit comments

Comments
 (0)