|
13 | 13 |
|
14 | 14 | def fahrenheit2celsius(temp):
|
15 | 15 | """
|
16 |
| - Returns temperature in Celsius. |
| 16 | + Returns temperature in Celsius given Fahrenheit temperature. |
17 | 17 | """
|
18 | 18 | return (5. / 9.) * (temp - 32)
|
19 | 19 |
|
20 | 20 |
|
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() |
28 | 34 |
|
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) |
31 | 39 |
|
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') |
36 | 43 |
|
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() |
40 | 45 |
|
41 |
| -plt.show() |
| 46 | +make_plot() |
0 commit comments