Fahrenheit Celsius Scales

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

The purpose of this lab is to demonstrate how to display two scales on the left and right y-axis. This example uses the Fahrenheit and Celsius scales. We will use a closure function to register as a callback to update the second axis according to the first axis.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Import necessary libraries

First, we need to import the numpy and matplotlib.pyplot libraries.

import matplotlib.pyplot as plt
import numpy as np

Define a function to convert Fahrenheit to Celsius

Next, we define a function to convert temperature in Fahrenheit to Celsius.

def fahrenheit2celsius(temp):
    """
    Returns temperature in Celsius given Fahrenheit temperature.
    """
    return (5. / 9.) * (temp - 32)

Define a function to update the second axis

We will define a closure function to register as a callback to update the second axis according to the first axis.

def convert_ax_c_to_celsius(ax_f):
    """
    Update second axis according to first axis.
    """
    y1, y2 = ax_f.get_ylim()
    ax_c.set_ylim(fahrenheit2celsius(y1), fahrenheit2celsius(y2))
    ax_c.figure.canvas.draw()

Create the plot

Now, we create a plot with two y-axes using the subplots() function of matplotlib.pyplot. We also connect the ylim_changed event of the first axis to the convert_ax_c_to_celsius() function.

fig, ax_f = plt.subplots()
ax_c = ax_f.twinx()

ax_f.callbacks.connect("ylim_changed", convert_ax_c_to_celsius)

Plot the data

We plot the data using the plot() function of the first axis.

ax_f.plot(np.linspace(-40, 120, 100))

Set the axis limits and labels

We set the x-axis limits to (0,100), and the y-axis labels and title.

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')

Display the plot

Finally, we display the plot using the show() function of matplotlib.pyplot.

plt.show()

Summary

In this lab, we learned how to display two scales on the left and right y-axis using Python Matplotlib. We used a closure function to register as a callback to update the second axis according to the first axis. This is useful when we want to plot two sets of data with different units.

Other Python Tutorials you may like