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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedPlottingGroup(["`Advanced Plotting`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/AdvancedPlottingGroup -.-> matplotlib/secondary_axis("`Secondary Axis`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/event_handling("`Event Handling`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48722{{"`Fahrenheit Celsius Scales`"}} matplotlib/figures_axes -.-> lab-48722{{"`Fahrenheit Celsius Scales`"}} matplotlib/line_plots -.-> lab-48722{{"`Fahrenheit Celsius Scales`"}} matplotlib/secondary_axis -.-> lab-48722{{"`Fahrenheit Celsius Scales`"}} matplotlib/event_handling -.-> lab-48722{{"`Fahrenheit Celsius Scales`"}} python/tuples -.-> lab-48722{{"`Fahrenheit Celsius Scales`"}} python/function_definition -.-> lab-48722{{"`Fahrenheit Celsius Scales`"}} python/importing_modules -.-> lab-48722{{"`Fahrenheit Celsius Scales`"}} python/numerical_computing -.-> lab-48722{{"`Fahrenheit Celsius Scales`"}} python/data_visualization -.-> lab-48722{{"`Fahrenheit Celsius Scales`"}} end

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