8000 Merge pull request #20759 from QuLogic/mathtext-example · sauerburger/matplotlib@7413aa9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7413aa9

Browse files
authored
Merge pull request matplotlib#20759 from QuLogic/mathtext-example
Modernize mathtext examples
2 parents 2ad9ec6 + 047cc7c commit 7413aa9

File tree

3 files changed

+94
-95
lines changed

3 files changed

+94
-95
lines changed

examples/text_labels_and_annotations/mathtext_asarray.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,11 @@ def text_to_rgba(s, *, dpi, **kwargs):
2121
# (If desired, one can also directly save the image to the filesystem.)
2222
fig = Figure(facecolor="none")
2323
fig.text(0, 0, s, **kwargs)
24-
buf = BytesIO()
25-
fig.savefig(buf, dpi=dpi, format="png", bbox_inches="tight", pad_inches=0)
26-
buf.seek(0)
27-
rgba = plt.imread(buf)
24+
with BytesIO() as buf:
25+
fig.savefig(buf, dpi=dpi, format="png", bbox_inches="tight",
26+
pad_inches=0)
27+
buf.seek(0)
28+
rgba = plt.imread(buf)
2829
return rgba
2930

3031

examples/text_labels_and_annotations/mathtext_examples.py

Lines changed: 82 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -5,121 +5,118 @@
55
66
Selected features of Matplotlib's math rendering engine.
77
"""
8-
import matplotlib.pyplot as plt
8+
import re
99
import subprocess
1010
import sys
11-
import re
1211

13-
# Selection of features following "Writing mathematical expressions" tutorial
14-
mathtext_titles = {
15-
0: "Header demo",
16-
1: "Subscripts and superscripts",
17-
2: "Fractions, binomials and stacked numbers",
18-
3: "Radicals",
19-
4: "Fonts",
20-
5: "Accents",
21-
6: "Greek, Hebrew",
22-
7: "Delimiters, functions and Symbols"}
23-
n_lines = len(mathtext_titles)
12+
import matplotlib.pyplot as plt
2413

25-
# Randomly picked examples
26-
mathext_demos = {
27-
0: r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = "
28-
r"U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} "
29-
r"\int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ "
30-
r"U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_"
31-
r"{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$",
3214

33-
1: r"$\alpha_i > \beta_i,\ "
34-
r"\alpha_{i+1}^j = {\rm sin}(2\pi f_j t_i) e^{-5 t_i/\tau},\ "
35-
r"\ldots$",
15+
# Selection of features following "Writing mathematical expressions" tutorial,
16+
# with randomly picked examples.
17+
mathtext_demos = {
18+
"Header demo":
19+
r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = "
20+
r"U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} "
21+
r"\int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ "
22+
r"U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_"
23+
r"{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$",
3624

37-
2: r"$\frac{3}{4},\ \binom{3}{4},\ \genfrac{}{}{0}{}{3}{4},\ "
38-
r"\left(\frac{5 - \frac{1}{x}}{4}\right),\ \ldots$",
25+
"Subscripts and superscripts":
26+
r"$\alpha_i > \beta_i,\ "
27+
r"\alpha_{i+1}^j = {\rm sin}(2\pi f_j t_i) e^{-5 t_i/\tau},\ "
28+
r"\ldots$",
3929

40-
3: r"$\sqrt{2},\ \sqrt[3]{x},\ \ldots$",
30+
"Fractions, binomials and stacked numbers":
31+
r"$\frac{3}{4},\ \binom{3}{4},\ \genfrac{}{}{0}{}{3}{4},\ "
32+
r"\left(\frac{5 - \frac{1}{x}}{4}\right),\ \ldots$",
4133

42-
4: r"$\mathrm{Roman}\ , \ \mathit{Italic}\ , \ \mathtt{Typewriter} \ "
43-
r"\mathrm{or}\ \mathcal{CALLIGRAPHY}$",
34+
"Radicals":
35+
r"$\sqrt{2},\ \sqrt[3]{x},\ \ldots$",
4436

45-
5: r"$\acute a,\ \bar a,\ \breve a,\ \dot a,\ \ddot a, \ \grave a, \ "
46-
r"\hat a,\ \tilde a,\ \vec a,\ \widehat{xyz},\ \widetilde{xyz},\ "
47-
r"\ldots$",
37+
"Fonts":
38+
r"$\mathrm{Roman}\ , \ \mathit{Italic}\ , \ \mathtt{Typewriter} \ "
39+
r"\mathrm{or}\ \mathcal{CALLIGRAPHY}$",
4840

49-
6: r"$\alpha,\ \beta,\ \chi,\ \delta,\ \lambda,\ \mu,\ "
50-
r"\Delta,\ \Gamma,\ \Omega,\ \Phi,\ \Pi,\ \Upsilon,\ \nabla,\ "
51-
r"\aleph,\ \beth,\ \daleth,\ \gimel,\ \ldots$",
41+
"Accents":
42+
r"$\acute a,\ \bar a,\ \breve a,\ \dot a,\ \ddot a, \ \grave a, \ "
43+
r"\hat a,\ \tilde a,\ \vec a,\ \widehat{xyz},\ \widetilde{xyz},\ "
44+
r"\ldots$",
5245

53-
7: r"$\coprod,\ \int,\ \oint,\ \prod,\ \sum,\ "
54-
r"\log,\ \sin,\ \approx,\ \oplus,\ \star,\ \varpropto,\ "
55-
r"\infty,\ \partial,\ \Re,\ \leftrightsquigarrow, \ \ldots$"}
46+
"Greek, Hebrew":
47+
r"$\alpha,\ \beta,\ \chi,\ \delta,\ \lambda,\ \mu,\ "
48+
r"\Delta,\ \Gamma,\ \Omega,\ \Phi,\ \Pi,\ \Upsilon,\ \nabla,\ "
49+
r"\aleph,\ \beth,\ \daleth,\ \gimel,\ \ldots$",
50+
51+
"Delimiters, functions and Symbols":
52+
r"$\coprod,\ \int,\ \oint,\ \prod,\ \sum,\ "
53+
r"\log,\ \sin,\ \approx,\ \oplus,\ \star,\ \varpropto,\ "
54+
r"\infty,\ \partial,\ \Re,\ \leftrightsquigarrow, \ \ldots$",
55+
}
56+
n_lines = len(mathtext_demos)
5657

5758

5859
def doall():
5960
# Colors used in Matplotlib online documentation.
60-
mpl_blue_rvb = (191. / 255., 209. / 256., 212. / 255.)
61-
mpl_orange_rvb = (202. / 255., 121. / 256., 0. / 255.)
62-
mpl_grey_rvb = (51. / 255., 51. / 255., 51. / 255.)
61+
mpl_grey_rgb = (51 / 255, 51 / 255, 51 / 255)
6362

6463
# Creating figure and axis.
65-
plt.figure(figsize=(6, 7))
66-
plt.axes([0.01, 0.01, 0.98, 0.90], facecolor="white", frameon=True)
67-
plt.gca().set_xlim(0., 1.)
68-
plt.gca().set_ylim(0., 1.)
69-
plt.gca().set_title("Matplotlib's math rendering engine",
70-
color=mpl_grey_rvb, fontsize=14, weight='bold')
71-
plt.gca().set_xticklabels([])
72-
plt.gca().set_yticklabels([])
64+
fig = plt.figure(figsize=(7, 7))
65+
ax = fig.add_axes([0.01, 0.01, 0.98, 0.90],
66+
facecolor="white", frameon=True)
67+
ax.set_xlim(0, 1)
68+
ax.set_ylim(0, 1)
69+
ax.set_title("Matplotlib's math rendering engine",
70+
color=mpl_grey_rgb, fontsize=14, weight='bold')
71+
ax.set_xticks([])
72+
ax.set_yticks([])
7373

7474
# Gap between lines in axes coords
7575
line_axesfrac = 1 / n_lines
7676

77-
# Plotting header demonstration formula
78-
full_demo = mathext_demos[0]
79-
plt.annotate(full_demo,
80-
xy=(0.5, 1. - 0.59 * line_axesfrac),
81-
color=mpl_orange_rvb, ha='center', fontsize=20)
77+
# Plot header demonstration formula.
78+
full_demo = mathtext_demos['Header demo']
79+
ax.annotate(full_demo,
80+
xy=(0.5, 1. - 0.59 * line_axesfrac),
81+
color='tab:orange', ha='center', fontsize=20)
82+
83+
# Plot feature demonstration formulae.
84+
for i_line, (title, demo) in enumerate(mathtext_demos.items()):
85+
print(i_line, demo)
86+
if i_line == 0:
87+
continue
8288

83-
# Plotting features demonstration formulae
84-
for i_line in range(1, n_lines):
8589
baseline = 1 - i_line * line_axesfrac
8690
baseline_next = baseline - line_axesfrac
87-
title = mathtext_titles[i_line] + ":"
88-
fill_color = ['white', mpl_blue_rvb][i_line % 2]
89-
plt.fill_between([0., 1.], [baseline, baseline],
90-
[baseline_next, baseline_next],
91-
color=fill_color, alpha=0.5)
92-
plt.annotate(title,
93-
xy=(0.07, baseline - 0.3 * line_axesfrac),
94-
color=mpl_grey_rvb, weight='bold')
95-
demo = mathext_demos[i_line]
96-
plt.annotate(demo,
97-
xy=(0.05, baseline - 0.75 * line_axesfrac),
98-
color=mpl_grey_rvb, fontsize=16)
99-
100-
for i in range(n_lines):
101-
s = mathext_demos[i]
102-
print(i, s)
91+
fill_color = ['white', 'tab:blue'][i_line % 2]
92+
ax.fill_between([0, 1], [baseline, baseline],
93+
[baseline_next, baseline_next],
94+
color=fill_color, alpha=0.2)
95+
ax.annotate(f'{title}:',
96+
xy=(0.06, baseline - 0.3 * line_axesfrac),
97+
color=mpl_grey_rgb, weight='bold')
98+
ax.annotate(demo,
99+
xy=(0.04, baseline - 0.75 * line_axesfrac),
100+
color=mpl_grey_rgb, fontsize=16)
101+
103102
plt.show()
104103

105104

106105
if '--latex' in sys.argv:
107106
# Run: python mathtext_examples.py --latex
108107
# Need amsmath and amssymb packages.
109-
fd = open("mathtext_examples.ltx", "w")
110-
fd.write("\\documentclass{article}\n")
111-
fd.write("\\usepackage{amsmath, amssymb}\n")
112-
fd.write("\\begin{document}\n")
113-
fd.write("\\begin{enumerate}\n")
114-
115-
for i in range(n_lines):
116-
s = mathext_demos[i]
117-
s = re.sub(r"(?<!\\)\$", "$$", s)
118-
fd.write("\\item %s\n" % s)
119-
120-
fd.write("\\end{enumerate}\n")
121-
fd.write("\\end{document}\n")
122-
fd.close()
108+
with open("mathtext_examples.ltx", "w") as fd:
109+
fd.write("\\documentclass{article}\n")
110+
fd.write("\\usepackage{amsmath, amssymb}\n")
111+
fd.write("\\begin{document}\n")
112+
fd.write("\\begin{enumerate}\n")
113+
114+
for s in mathtext_demos.values():
115+
s = re.sub(r"(?<!\\)\$", "$$", s)
116+
fd.write("\\item %s\n" % s)
117+
118+
fd.write("\\end{enumerate}\n")
119+
fd.write("\\end{document}\n")
123120

124121
subprocess.call(["pdflatex", "mathtext_examples.ltx"])
125122
else:

examples/text_labels_and_annotations/mathtext_fontfamily_example.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,25 +13,26 @@
1313

1414
import matplotlib.pyplot as plt
1515

16-
plt.figure(figsize=(6, 5))
16+
17+
fig, ax = plt.subplots(figsize=(6, 5))
1718

1819
# A simple plot for the background.
19-
plt.plot(range(11), color="0.9")
20+
ax.plot(range(11), color="0.9")
2021

2122
# A text mixing normal text and math text.
2223
msg = (r"Normal Text. $Text\ in\ math\ mode:\ "
2324
r"\int_{0}^{\infty } x^2 dx$")
2425

2526
# Set the text in the plot.
26-
plt.text(1, 7, msg, size=12, math_fontfamily='cm')
27+
ax.text(1, 7, msg, size=12, math_fontfamily='cm')
2728

2829
# Set another font for the next text.
29-
plt.text(1, 3, msg, size=12, math_fontfamily='dejavuserif')
30+
ax.text(1, 3, msg, size=12, math_fontfamily='dejavuserif')
3031

3132
# *math_fontfamily* can be used in most places where there is text,
3233
# like in the title:
33-
plt.title(r"$Title\ in\ math\ mode:\ \int_{0}^{\infty } x^2 dx$",
34-
math_fontfamily='stixsans', size=14)
34+
ax.set_title(r"$Title\ in\ math\ mode:\ \int_{0}^{\infty } x^2 dx$",
35+
math_fontfamily='stixsans', size=14)
3536

3637
# Note that the normal text is not changed by *math_fontfamily*.
3738
plt.show()

0 commit comments

Comments
 (0)
0