Skip to content

Commit 5a550f2

Browse files
committed
ENH: Add the space_sep option to EngFormatter, and docstring updates
1 parent cf43f81 commit 5a550f2

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

lib/matplotlib/ticker.py

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1192,6 +1192,9 @@ class EngFormatter(Formatter):
11921192
`places` is the precision with which to display the number,
11931193
specified in digits after the decimal point (there will be between
11941194
one and three digits before the decimal point).
1195+
1196+
`space_sep` controls if there is a space between the number and the
1197+
prefix/unit. For example, '3.14 mV' if True and '3.14mV' if False.
11951198
"""
11961199
# The SI engineering prefixes
11971200
ENG_PREFIXES = {
@@ -1214,9 +1217,27 @@ class EngFormatter(Formatter):
12141217
24: "Y"
12151218
}
12161219

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

12211242
def __call__(self, x, pos=None):
12221243
s = "%s%s" % (self.format_eng(x), self.unit)
@@ -1260,18 +1281,20 @@ def format_eng(self, num):
12601281

12611282
mant = sign * dnum / (10 ** pow10)
12621283

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

12701293
formatted = format_str % (mant, prefix)
12711294

12721295
formatted = formatted.strip()
12731296
if (self.unit != "") and (prefix == self.ENG_PREFIXES[0]):
1274-
formatted = formatted + " "
1297+
formatted = formatted + self.sep
12751298

12761299
return formatted
12771300

0 commit comments

Comments
 (0)