Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9225aec

Browse files
committed
Make the formatting more explicit
This avoids exponential notation (which is supported by PS but who knows how all the different parsers react to it) and trailing zeros, so we don't unnecessarily increase the size of fonts that have a nice [0.001 0 0 0.001] matrix. Encapsulate the formatting operation in a cbook function and give it a unit test.
1 parent 013d508 commit 9225aec

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

lib/matplotlib/cbook/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2383,3 +2383,11 @@ def _setup_new_guiapp():
23832383
except OSError:
23842384
_c_internal_utils.Win32_SetCurrentProcessExplicitAppUserModelID(
23852385
"matplotlib")
2386+
2387+
2388+
def format_approx(number, precision):
2389+
"""
2390+
Format the number with at most the number of decimals given as precision.
2391+
Remove trailing zeros and possibly the decimal point.
2392+
"""
2393+
return f'{number:.{precision}f}'.rstrip('0').rstrip('.') or '0'

lib/matplotlib/tests/test_cbook.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,3 +741,15 @@ def verify_pre_post_state(obj):
741741
assert a.static == 'static'
742742

743743
verify_pre_post_state(a)
744+
745+
746+
def test_format_approx():
747+
f = cbook.format_approx
748+
assert f(0, 1) == '0'
749+
assert f(0, 2) == '0'
750+
assert f(0, 3) == '0'
751+
assert f(-0.0123, 1) == '-0'
752+
assert f(1e-7, 5) == '0'
753+
assert f(0.0012345600001, 5) == '0.00123'
754+
assert f(-0.0012345600001, 5) == '-0.00123'
755+
assert f(0.0012345600001, 8) == f(0.0012345600001, 10) == '0.00123456'

lib/matplotlib/type1font.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929

3030
import numpy as np
3131

32+
from matplotlib.cbook import format_approx
33+
3234

3335
# token types
3436
_TokenType = enum.Enum('_TokenType',
@@ -269,7 +271,7 @@ def fontmatrix(array):
269271
array[::2] = newmatrix[0:3, 0]
270272
array[1::2] = newmatrix[0:3, 1]
271273
return (
272-
'[' + ' '.join(f'{x:.5g}' for x in array) + ']'
274+
'[%s]' % ' '.join(format_approx(x, 6) for x in array)
273275
).encode('ascii')
274276

275277
def replace(fun):

0 commit comments

Comments
 (0)