How to clear a plot in Matplotlib in Python

Matplotlib is a graphing library that involves plotting various graphs and charts. Often during run-time, we may wish to change which graph is being displayed. Instead of closing the whole window and opening a new matplotlib window, we can just clear the old plot and plot a new one.

Let’s explore how we can do so.


Clear a Plot in Matplotlib with clf()

In order to clear the currently drawn Graph/Chart, we can use the clf() function (Which I believe stands for “clear figure“).

An example of how it may be used it as follows:

import matplotlib.pyplot as plt

f1 = plt.figure()
plt.plot([1, 2, 3])

plt.clf()
plt.show()

This will produce the following output:

Clear a Plot in Matplotlib with clf()

As you can see here, the whole graph has been wiped out. Both the axes and the figure have been cleared.

That wasn’t a very great example though as the graph was cleared right from the start. Here is another example which uses matplotlib’s animation module to clear the graph after a second.

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def input_func(n):
    plt.clf()

f1 = plt.figure()
plt.plot([1, 2, 3])

animation = FuncAnimation(f1, input_func, range(1), interval = 1000)
plt.show()

Try running this code yourself to see its effect.


Clear Axes in Matplotlib with cla()

Removing the entire figure along with the axes can make the result look a bit awkward. If you want to leave the axes in, while only clearing the graph/chart, then use cla() instead.

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def input_func(e):
    plt.cla()

f1 = plt.figure()
plt.plot([1, 2, 3])

animation = FuncAnimation(f1, input_func, range(1), interval = 1000)
plt.show()

The output:


This marks the end of the How to clear a plot in Matplotlib in Python Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments