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

Skip to content

Commit 5d8d948

Browse files
committed
Simplify contour_label_demo.
Using a custom float subclass is very overkill, one can simply use a custom formatter.
1 parent 48031d8 commit 5d8d948

File tree

1 file changed

+8
-18
lines changed

1 file changed

+8
-18
lines changed

examples/images_contours_and_fields/contour_label_demo.py

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -27,32 +27,22 @@
2727
Z = (Z1 - Z2) * 2
2828

2929
###############################################################################
30-
# Make contour labels using creative float classes
31-
# Follows suggestion of Manuel Metz
30+
# Make contour labels wuth custom level formatters
3231

33-
# Define a class that forces representation of float to look a certain way
34-
# This remove trailing zero so '1.0' becomes '1'
3532

36-
37-
class nf(float):
38-
def __repr__(self):
39-
s = f'{self:.1f}'
40-
return f'{self:.0f}' if s[-1] == '0' else s
33+
# This custom formatter removes trailing zeros, e.g. "1.0" becomes "1", and
34+
# then adds a percent sign.
35+
def fmt(x):
36+
s = f"{x:.1f}"
37+
if s.endswith("0"):
38+
s = f"{x:.0f}"
39+
return rf"{s} \%" if plt.rcParams["text.usetex"] else f"{s} %"
4140

4241

4342
# Basic contour plot
4443
fig, ax = plt.subplots()
4544
CS = ax.contour(X, Y, Z)
4645

47-
# Recast levels to new class
48-
CS.levels = [nf(val) for val in CS.levels]
49-
50-
# Label levels with specially formatted floats
51-
if plt.rcParams["text.usetex"]:
52-
fmt = r'%r \%%'
53-
else:
54-
fmt = '%r %%'
55-
5646
ax.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10)
5747

5848
###############################################################################

0 commit comments

Comments
 (0)