8000 ENH: Add the space_sep option to EngFormatter, and docstring updates · matplotlib/matplotlib@99b590c · GitHub
[go: up one dir, main page]

Skip to content

Commit 99b590c

Browse files
committed
ENH: Add the space_sep option to EngFormatter, and docstring updates
1 parent 0ac187d commit 99b590c

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
@@ -1036,6 +1036,9 @@ class EngFormatter(Formatter):
10361036
`places` is the precision with which to display the number,
10371037
specified in digits after the decimal point (there will be between
10381038
one and three digits before the decimal point).
1039+
1040+
`space_sep` controls if there is a space between the number and the
1041+
prefix/unit. For example, '3.14 mV' if True and '3.14mV' if False.
10391042
"""
10401043
# The SI engineering prefixes
10411044
ENG_PREFIXES = {
@@ -1058,9 +1061,27 @@ class EngFormatter(Formatter):
10581061
24: "Y"
10591062
}
10601063

1061-
def __init__(self, unit="", places=None):
1064+
def __init__(self, unit="", places=None, space_sep=True):
1065+
""" Parameters
1066+
----------
1067+
unit: str (default: u"")
1068+
Unit symbol to use.
1069+
1070+
places: int (default: None)
1071+
Precision, i.e. number of digits after the decimal point.
1072+
If it is None, falls back to the floating point format '%g'.
1073+
1074+
space_sep: boolean (default: True)
1075+
If True, a (single) space is used between the value and the
1076+
prefix/unit, else the prefix/unit is directly appended to the
1077+
value.
1078+
"""
10621079
self.unit = unit
10631080
self.places = places
1081+
if space_sep is True:
1082+
self.sep = u" " # 1 space
1083+
else:
1084+
self.sep = u"" # no space
10641085

10651086
def __call__(self, x, pos=None):
10661087
s = "%s%s" % (self.format_eng(x), self.unit)
@@ -1104,18 +1125,20 @@ def format_eng(self, num):
11041125

11051126
mant = sign * dnum / (10 ** pow10)
11061127

1128+
# TODO: shouldn't we raise a warning if self.places < 0?
11071129
if self.places is None:
1108-
format_str = "%g %s"
1130+
format_str = "%g{sep:s}%s".format(sep=self.sep)
11091131
elif self.places == 0:
1110-
format_str = "%i %s"
1132+
format_str = "%d{sep:s}%s".format(sep=self.sep)
11111133
elif self.places > 0:
1112-
format_str = ("%%.%if %%s" % self.places)
1134+
format_str = "%.{p:d}f{sep:s}%s".format(p=self.places,
1135+
sep=self.sep)
11131136

11141137
formatted = format_str % (mant, prefix)
11151138

11161139
formatted = formatted.strip()
11171140
if (self.unit != "") and (prefix == self.ENG_PREFIXES[0]):
1118-
formatted = formatted + " "
1141+
formatted = formatted + self.sep
11191142

11201143
return formatted
11211144

0 commit comments

Comments
 (0)
0