Как очистить график в питоне
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
matplotlib.figure.Figure.clear() function
The clear() method figure module of matplotlib library is used to Clear the figure.
Syntax: clear(self, keep_observers=False)
Parameters: This accept the following parameters that are described below:
How to clear the memory completely of all Matplotlib plots?
Using the following methods, we can clear the memory occupied by Matplotlib plots.
plt.figure() — Create a new figure or activate an existing figure.
plt.figure().close() — Close a figure window.
close() by itself closes the current figure
close(h), where h is a Figure instance, closes that figure
close(num) closes the figure number, num
close(name), where name is a string, closes figure with that label
Как очистить участок в Matplotlib С помощью метода clear()
Примеры Matplotlib clear plot в Python с использованием axes.clear() и figure.clear (), которые очищают текущие оси и фигуру соответственно.
- Автор записи
Как очистить участок в Matplotlib С помощью метода clear()
Здравствуйте программисты, в сегодняшней статье мы обсудим Matplotlib clear plot в python. Matplotlib – это библиотека на Python, которая является численно- математическим расширением для библиотеки NumPy. Модуль figure библиотеки Matplotlib предоставляет художника верхнего уровня, фигуру, которая содержит все элементы сюжета. Модуль figure используется для управления интервалом между подзаголовками по умолчанию и контейнером верхнего уровня для всех элементов графика.
Класс Axes содержит элементы рисунка: Axis, Tick, Line2D, Text, Polygon и т. Д., а также задает систему координат. Экземпляры Axes поддерживают обратные вызовы через атрибут callbacks. Функция Axes.clear() в модуле axes библиотеки matplotlib используется для очистки осей. Таким образом, Matplotlib figure.clear() и axes.clear() используются для очистки фигуры и осей соответственно. Вот синтаксис и параметры функции Matplotlib clear plot.
Синтаксис Matplotlib clear plot в Python
Параметр
Функция axis.clear() не принимает никаких параметров. Параметр ‘keep_observers’ на рис.clear() является логическим значением.
Тип возврата
Функция clear() не возвращает никакого значения. Он используется в программах python для очистки графиков.
Пример Matplotlib Рисунок четкий график
Объяснение:
В приведенном выше примере мы сначала создаем график в соответствии со значениями данных, заданными в качестве входных данных.xlabel-это “ось x”, а ylabel-“ось y”. Название рисунка- ” matplotlib.figure.Рис.Пример функции clear ()’. Линии сетки также строятся для рисунка, устанавливая ax.grid(True). Но перед оператором plot.show (), который показывает построенную фигуру, мы используем функцию fig.clear (). Рис.clear() href=”https://en.wikipedia.org/wiki/Function”>функция очищает график фигуры, когда “True” является аргументом. Таким образом, в этом примере, поскольку рис.clear(True) находится перед plot.show(), выходным является вся текущая фигура clear, за исключением заголовка рисунка. href=”https://en.wikipedia.org/wiki/Function”>функция очищает график фигуры, когда “True” является аргументом. Таким образом, в этом примере, поскольку рис.clear(True) находится перед plot.show(), выходным является вся текущая фигура clear, за исключением заголовка рисунка.
Пример четкого графика оси Matplotlib
Объяснение:
В приведенном выше примере создаются два графика “ax” и “ax 1”. Метка на рис. 1-“ось y”. Matplotlib grid() также имеет значение “True”, которое возвращает линии сетки для рисунка. Также упоминается название рисунка. Но мы не используем функцию Matplotlib clear() с сюжетом “ax”. Для второго рисунка мы построим его в соответствии с заданными входными значениями. Но поскольку используется ax2.clear (), текущий график фигуры ” ax2 ” очищается, за исключением его названия. Наконец, оператор plt.show() дает фигуру ” ax “и очищает фигуру” ax2 ” только с ее названием.
Должен Читать
- Как очистить оболочку Python наиболее эффективным способом
- Matplotlib Savefig() Для различных параметров в Python
- Ось Numpy в Python С подробными Примерами
Вывод
В этой статье мы обсудили способы Matplotlib clear plot в Python. Функция clear() в виде axes.clear() или figure.clear() очищает оси и фигуру графика соответственно. Мы ясно обсудили обе оси и ясно изобразили их с примерами и объяснениями. Функция Matplotlib cla() может быть использована в качестве функции axes.clear (). Аналогично, функция clf() делает рисунок ясным. И cla() , и clf() очищают сюжет в Matplotlib.
Однако, если у вас есть какие-либо сомнения или вопросы, дайте мне знать в разделе комментариев ниже. Я постараюсь помочь вам как можно скорее.
How to Clear Plot in Matplotlib Using clear() Method

Hello programmers, in today’s article, we will discuss Matplotlib clear plot in python. Matplotlib is a library in Python, which is a numerical – mathematical extension for NumPy library. The figure module of the Matplotlib library provides the top-level Artist, the Figure, which contains all the plot elements. The figure module is used to control the subplots’ default spacing and top-level container for all plot elements.
The Axes Class contains the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. The instances of Axes supports callbacks through a callbacks attribute. The Axes.clear() in the axes module of the matplotlib library is used to clear the axes. Thus, the Matplotlib figure.clear() and axes.clear() is used to clear figure and axes, respectively. Here are the syntax and parameters of the Matplotlib clear plot function.
Syntax of Matplotlib clear plot in Python
Parameter
The axis.clear() function accepts no parameters.
The ‘keep_observers’ parameter in figure.clear() function is a boolean value.
Return type
The clear() function does not return any value. It is used in python programs to clear plots.
Example of Matplotlib Figure clear plot
Output:

Explanation:
In the above example, we first create a plot as per data values given as input.The xlabel is ‘x-axis,’ and the ylabel is ‘y-axis.’ The title of the figure is ‘matplotlib.figure.Figure.clear() function Example’. The gridlines are also plotted for the figure by setting ax.grid(True). But before the plt.show() statement that shows the plotted figure, we use the fig.clear() function. The fig.clear() function clears the figure plot when ‘True’ is an argument. Thus, in this example, since fig.clear(True) is before the plt.show(), the output is the entire clear current figure except the figure title.
Example of Matplotlib Axis clear plot
Output:

Explanation:
In the above example, the two plots ‘ax’ and ‘ax1’ are created. The ylabel of figure 1 is ‘y-axis.’ The Matplotlib grid() is also ‘True,’ which returns grid lines for the figure. Also, the title of the figure is mentioned. But, we do not use the Matplotlib clear() function with the ‘ax’ plot. For the second figure, we plot it as per the given input values. But since the ax2.clear() is used, the current ‘ax2’ figure plot is cleared except for its title. Finally, the plt.show() statement gives the ‘ax’ figure and clears the ‘ax2’ figure with just its title.
Must Read
Conclusion
In this article, we have discussed ways of Matplotlib clear plot in Python. The clear() function as axes.clear() or figure.clear() clears the axes and figure of the plot, respectively. We have discussed both axes clearly and figure clear with examples and explanations. The Matplotlib cla() function can be used as axes.clear() function. Similarly, the clf() function makes figure clear. Both cla() and clf() clears plot in Matplotlib.
However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.