Introduction
This lab aims to explain how to use general timer objects in Matplotlib. This is a simple example that is used to update the time placed in the title of the figure.
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 Required Libraries
Import the required libraries for the code to function properly.
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
Define Function to Update Title
Define the function to update the title of the figure with the current time.
def update_title(axes):
axes.set_title(datetime.now())
axes.figure.canvas.draw()
Create Figure and Axes
Create a figure and axes for the plot.
fig, ax = plt.subplots()
Plot Data
Create data to plot and plot it on the axes.
x = np.linspace(-3, 3)
ax.plot(x, x ** 2)
Create Timer Object
Create a new timer object. Set the interval to 100 milliseconds (1000 is default) and tell the timer what function should be called.
timer = fig.canvas.new_timer(interval=100)
timer.add_callback(update_title, ax)
Start Timer
Start the timer.
timer.start()
Show Plot
Show the plot.
plt.show()
Summary
This lab showed how to use general timer objects in Matplotlib to update the time in the title of a figure. By following the steps, users can create their own timer objects and update their plots dynamically.