Matplotlib, as a Python plotting library, is known for its capability to produce high-quality figures. Beyond static images, Matplotlib can also plot simple animations. While it doesn’t adopt OpenGL for high-performance graphics like VisPy, it is still sufficiently for basic academic and research applications. This post turn a default Matplotlib example into a straightforward CPU monitor and introduces the basics of Matplotlib animation functions.
Before diving in, we should explore Matplotlib animation function: matplotlib.animation.FuncAnimation
. This function is very straightforward. Here’s an overview of its parameters:
1 |
|
It is worth noting that **kwargs
contains additional parameters, including the commonly used interval parameter, which sets the refresh rate in milliseconds. During refresh, FuncAnimation
invokes the func
function and plots based on frames, which can be an iterator, generator, or a sequence of frames.
We can start with implementing a basic animation, as shown below,
Implementation code,
1 |
|
The code utilizes a generator to produce frames, with a sampling interval of 100ms. This means the image is redrawn every 100ms. Since this example randomly generates drawings, we need to employ Python psutil module for actual CPU monitoring. Using the cpu_percent
function from psutil, we can fetch the CPU usage rate as well as set an interval, which I currently set it as 1s to prevent slowing the system. By synchronizing the frame refresh rate with this interval, we can effectively achieve CPU monitoring capabilities,
1 |
|
Comparing it with the Task Manager,
The Task Manager seems to sample every 0.5s, its display might appear more accurate. To shorten the monitoring interval, simply adjust the interval settings in the cpu_percent
function and the frame refresh rate in the code above.
Besides using above method for animation, the graphic refreshes can also be achieved with blit
. However, this method has a drawback: it prevents interaction with the graph during animation, and causes the process to freeze despite the impressive display effect. Here is an example,
All source code is available upon request.