From 53d68db9fa3464b37781ef35190a4e54ef9d2fe0 Mon Sep 17 00:00:00 2001 From: Gustavo Braganca Date: Sun, 2 Feb 2014 21:01:55 +0100 Subject: [PATCH] Scipy2013 Sprint: Cleaning F/C example I cleaned the F/C example as suggested in the Scipy 2013 sprint. I had the help of @leouieda on this. For more information, please see #2181. --- examples/api/fahrenheit_celsius_scales.py | 27 -------------- .../fahrenheit_celsius_scales.py | 37 +++++++++++++++++++ 2 files changed, 37 insertions(+), 27 deletions(-) delete mode 100644 examples/api/fahrenheit_celsius_scales.py create mode 100644 examples/subplots_axes_and_figures/fahrenheit_celsius_scales.py diff --git a/examples/api/fahrenheit_celsius_scales.py b/examples/api/fahrenheit_celsius_scales.py deleted file mode 100644 index 72a52f4fa41b..000000000000 --- a/examples/api/fahrenheit_celsius_scales.py +++ /dev/null @@ -1,27 +0,0 @@ -""" -Show how to display two scales on the left and right y axis -- Fahrenheit and Celsius -""" - -import matplotlib.pyplot as plt - -fig, ax1 = plt.subplots() # ax1 is the Fahrenheit scale -ax2 = ax1.twinx() # ax2 is the Celsius scale - -def Tc(Tf): - return (5./9.)*(Tf-32) - - -def update_ax2(ax1): - y1, y2 = ax1.get_ylim() - ax2.set_ylim(Tc(y1), Tc(y2)) - ax2.figure.canvas.draw() - -# automatically update ylim of ax2 when ylim of ax1 changes. -ax1.callbacks.connect("ylim_changed", update_ax2) -ax1.plot([78, 79, 79, 77]) - -ax1.set_title('Two scales: Fahrenheit and Celsius') -ax1.set_ylabel('Fahrenheit') -ax2.set_ylabel('Celsius') - -plt.show() diff --git a/examples/subplots_axes_and_figures/fahrenheit_celsius_scales.py b/examples/subplots_axes_and_figures/fahrenheit_celsius_scales.py new file mode 100644 index 000000000000..2318f1678671 --- /dev/null +++ b/examples/subplots_axes_and_figures/fahrenheit_celsius_scales.py @@ -0,0 +1,37 @@ +""" +Demo of how to display two scales on the left and right y axis. + +This example uses the Fahrenheit and Celsius scales. +""" +import matplotlib.pyplot as plt +import numpy as np + + +def fahrenheit2celsius(temp): + """ + Returns temperature in Celsius. + """ + return (5. / 9.) * (temp - 32) + + +def convert_ax_c_to_celsius(ax_f): + """ + Update second axis according with first axis. + """ + y1, y2 = ax_f.get_ylim() + ax_c.set_ylim(fahrenheit2celsius(y1), fahrenheit2celsius(y2)) + ax_c.figure.canvas.draw() + +fig, ax_f = plt.subplots() +ax_c = ax_f.twinx() + +# automatically update ylim of ax2 when ylim of ax1 changes. +ax_f.callbacks.connect("ylim_changed", convert_ax_c_to_celsius) +ax_f.plot(np.linspace(-40, 120, 100)) +ax_f.set_xlim(0, 100) + +ax_f.set_title('Two scales: Fahrenheit and Celsius') +ax_f.set_ylabel('Fahrenheit') +ax_c.set_ylabel('Celsius') + +plt.show()