8000 DOC: Make temperature scale example use a closure for easier reusabil… · matplotlib/matplotlib@28fde25 · GitHub
[go: up one dir, main page]

Skip to content

Commit 28fde25

Browse files
authored
DOC: Make temperature scale example use a closure for easier reusability (#14594)
DOC: Make temperature scale example use a closure for easier reusability
2 parents b53418e + 58f1813 commit 28fde25

File tree

1 file changed

+23
-18
lines changed

1 file changed

+23
-18
lines changed

examples/subplots_axes_and_figures/fahrenheit_celsius_scales.py

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -13,29 +13,34 @@
1313

1414
def fahrenheit2celsius(temp):
1515
"""
16-
Returns temperature in Celsius.
16+
Returns temperature in Celsius given Fahrenheit temperature.
1717
"""
1818
return (5. / 9.) * (temp - 32)
1919

2020

21-
def convert_ax_c_to_celsius(ax_f):
22-
"""
23-
Update second axis according with first axis.
24-
"""
25-
y1, y2 = ax_f.get_ylim()
26-
ax_c.set_ylim(fahrenheit2celsius(y1), fahrenheit2celsius(y2))
27-
ax_c.figure.canvas.draw()
21+
def make_plot():
22+
23+
# Define a closure function to register as a callback
24+
def convert_ax_c_to_celsius(ax_f):
25+
"""
26+
Update second axis according with first axis.
27+
"""
28+
y1, y2 = ax_f.get_ylim()
29+
ax_c.set_ylim(fahrenheit2celsius(y1), fahrenheit2celsius(y2))
30+
ax_c.figure.canvas.draw()
31+
32+
fig, ax_f = plt.subplots()
33+
ax_c = ax_f.twinx()
2834

29-
fig, ax_f = plt.subplots()
30-
ax_c = ax_f.twinx()
35+
# automatically update ylim of ax2 when ylim of ax1 changes.
36+
ax_f.callbacks.connect("ylim_changed", convert_ax_c_to_celsius)
37+
ax_f.plot(np.linspace(-40, 120, 100))
38+
ax_f.set_xlim(0, 100)
3139

32-
# automatically update ylim of ax2 when ylim of ax1 changes.
33-
ax_f.callbacks.connect("ylim_changed", convert_ax_c_to_celsius)
34-
ax_f.plot(np.linspace(-40, 120, 100))
35-
ax_f.set_xlim(0, 100)
40+
ax_f.set_title('Two scales: Fahrenheit and Celsius')
41+
ax_f.set_ylabel('Fahrenheit')
42+
ax_c.set_ylabel('Celsius')
3643

37-
ax_f.set_title('Two scales: Fahrenheit and Celsius')
38-
ax_f.set_ylabel('Fahrenheit')
39-
ax_c.set_ylabel('Celsius')
44+
plt.show()
4045

41-
plt.show()
46+
make_plot()

0 commit comments

Comments
 (0)
0