Как очистить график в matplotlib

How to remove lines in a Matplotlib plot

How can I remove a line (or lines) of a matplotlib axes in such a way as it actually gets garbage collected and releases the memory back? The below code appears to delete the line, but never releases the memory (even with explicit calls to gc.collect() )

So is there a way to just delete one line from an axes and get the memory back? This potential solution also does not work.

Как очистить график в matplotlib

6 Answers 6

This is a very long explanation that I typed up for a coworker of mine. I think it would be helpful here as well. Be patient, though. I get to the real issue that you are having toward the end. Just as a teaser, it’s an issue of having extra references to your Line2D objects hanging around.

WARNING: One other note before we dive in. If you are using IPython to test this out, IPython keeps references of its own and not all of them are weakrefs. So, testing garbage collection in IPython does not work. It just confuses matters.

We start out by creating a Figure object, then add an Axes object to that figure. Note that ax and fig.axes[0] are the same object (same id() ).

This also extends to lines in an axes object:

If you were to call plt.show() using what was done above, you would see a figure containing a set of axes and a single line:

Как очистить график в matplotlib

Now, while we have seen that the contents of lines and ax.lines is the same, it is very important to note that the object referenced by the lines variable is not the same as the object reverenced by ax.lines as can be seen by the following:

As a consequence, removing an element from lines does nothing to the current plot, but removing an element from ax.lines removes that line from the current plot. So:

So, if you were to run the second line of code, you would remove the Line2D object contained in ax.lines[0] from the current plot and it would be gone. Note that this can also be done via ax.lines.remove() meaning that you can save a Line2D instance in a variable, then pass it to ax.lines.remove() to delete that line, like so:

Как очистить график в matplotlib

Как очистить график в matplotlib

All of the above works for fig.axes just as well as it works for ax.lines

Now, the real problem here. If we store the reference contained in ax.lines[0] into a weakref.ref object, then attempt to delete it, we will notice that it doesn’t get garbage collected:

The reference is still live! Why? This is because there is still another reference to the Line2D object that the reference in wr points to. Remember how lines didn’t have the same ID as ax.lines but contained the same elements? Well, that’s the problem.

So, the moral of the story is, clean up after yourself. If you expect something to be garbage collected but it isn’t, you are likely leaving a reference hanging out somewhere.

Источник

Как очистить участок в 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 ” только с ее названием.

Должен Читать

Вывод

Однако, если у вас есть какие-либо сомнения или вопросы, дайте мне знать в разделе комментариев ниже. Я постараюсь помочь вам как можно скорее.

Источник

How To Clear A Plot In Python

Как очистить график в matplotlib

Before we start: This Python tutorial is a part of our series of Python Package tutorials. You can find other Matplotlib related topics too!

Matplotlib is a data visualization and graphical plotting library for Python. Matplotlib’s pyplot API is stateful, which means that it stores the state of objects until a method is encountered that will clear the current state.

This article focuses on how to clear a plot by clearing the current Axes and Figure state of a plot, without closing the plot window. There are two methods available for this purpose:

How to Clear a Pyplot Figure

You can use the matplotlib.pyplot.clf() function to clear the current Figure’s state. The following example shows how to create two identical Figures simultaneously, and then apply the clf() function only to Figure 2:

Figure 1. A Figure not cleared with the clf() function:

Как очистить график в matplotlib

Figure 2. A Figure with the same elements cleared with the clf() function:

Как очистить график в matplotlib

How to Clear Pyplot Axes

Axes is a container class within the top-level Figure container. It is the data plotting area in which most of the elements in a plot are located, including Axis, Tick, Line2D, Text, etc., and it also sets the coordinates. An Axes has at least an X-Axis and a Y-Axis, and may have a Z-Axis.

The following example creates a Figure and then plots two Axes in two different subplots. Only the second Axes is cleared with the cla() function:

Figure 3. A Figure containing two Axes in different subplots. The first Axes is not cleared with the cla() function. The second Axes is cleared with cla():

Как очистить график в matplotlib

The following tutorials will provide you with step-by-step instructions on how to work with Matplotlib, including:

Use ActiveState Python and accelerate your Python Data Science projects.

ActiveState Python is 100% compatible with the open source Python distribution, and provides the security and commercial support that your organization requires.

With ActiveState Python you can explore and manipulate data, run statistical analysis, and deliver visualizations to share insights with your business users and executives sooner–no matter where your data lives.

Источник

How to Clear Plot in Matplotlib Using clear() Method

Как очистить график в matplotlib

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:

Как очистить график в matplotlib

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:

Как очистить график в matplotlib

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.

Источник

Matplotlib. Урок 2. Работа с инструментом pyplot

Основы работы с pyplot

Построение графиков

В результате будет выведено пустое поле:

Как очистить график в matplotlib

Если в качестве параметра функции plot() передать список, то значения из этого списка будут отложены по оси ординат (ось y ), а по оси абсцисс (ось x ) будут отложены индексы элементов массива:

Как очистить график в matplotlib

Для того, чтобы задать значения по осям x и y необходимо в plot() передать два списка:

Как очистить график в matplotlib

Текстовые надписи на графике

Наиболее часто используемые текстовые надписи на графике это:

Рассмотрим кратко данные элементы, более подробный рассказ о них будет в одном из ближайших уроков.

Наименование осей

Для функций xlabel()/ylabel() основными являются следующие аргументы:

Аргументов у этих функций довольно много и они позволяют достаточно тонко настроить внешний вид надписей. В рамках этого урока мы только начинаем знакомиться с инструментом pyplot поэтому не будем приводить весь список.

Заголовок графика

Для задания заголовка графика используется функция title() :

Из параметров отметим следующие:

Текстовое примечание

Легенда

Разместим на уже знакомом нам графике необходимый набор подписей.

Как очистить график в matplotlib

Работа с линейным графиком

В этом параграфе мы рассмотрим основные параметры и способы их задания для изменения внешнего вида линейного графика. Matplotlib предоставляет огромное количество инструментов для построения различных видов графиков. Так как наиболее часто встречающийся вид графика – это линейный, ему и уделим внимание. Необходимо помнить, что настройка графиков других видов, будет осуществляться сходным образом.

Параметры, которые отвечают за отображение графика можно задать непосредственно в самой функции plot() :

Стиль линии графика

Значение параметраОписание
‘-‘ или ‘solid’Непрерывная линия
‘–‘ или ‘dashed’Штриховая линия
‘-.’ или ‘dashdot’Штрихпунктирная линия
‘:’ или ‘dotted’Пунктирная линия
‘None’ или ‘ ‘ или ”Не отображать линию

Как очистить график в matplotlib

Либо можно воспользоваться функцией setp() :

Результат будет тот же, что на рисунке выше.

Как очистить график в matplotlib

Тот же результат можно получить, вызвав plot() для построения каждого графика по отдельности. Если вы хотите представить каждый график отдельно на своем поле, то используйте для этого subplot() (см. Размещение графиков на разных полях)

Цвет линии

Например штриховая красная линия будет задаваться так: ‘–r’, а штрих пунктирная зеленая так ‘-.g’

Как очистить график в matplotlib

Тип графика

До этого момента мы работали только с линейными графиками, функция plot() позволяет задать тип графика: линейный либо точечный, при этом для точечного графика можно указать соответствующий маркер. Приведем пару примеров:

Как очистить график в matplotlib

Как очистить график в matplotlib

Размер маркера можно менять, об этом более подробно будет рассмотрено в уроке, посвященном точечным графикам.

Размещение графиков на разных полях

Существуют три основных подхода к размещению нескольких графиков на разных полях:

В этом уроке будут рассмотрены первые два подхода.

Работа с функцией subplot()

После задания размера, указывается местоположение, куда будет установлено поле с графиком с помощью функции subplot(). Чаще всего используют следующие варианты вызова subplot:

subplot(nrows, ncols, index)

Рассмотрим на примере работу с данными функциями:

Как очистить график в matplotlib

Второй вариант использования subplot():

Работа с функцией subplots()

Решим задачу вывода четырех графиков с помощью функции subplots() :

Результат будет аналогичный тому, что приведен в разделе “Работа с функцией subplot() ”.

P.S.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *