Skip to content

Commit b122639

Browse files
jklymakmeeseeksmachine
authored andcommitted
Backport PR #30244: DOC: Recommend to use bare Figure instances for saving to file
1 parent 8b0808e commit b122639

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

doc/users/faq.rst

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -281,8 +281,23 @@ locators as desired because the two axes are independent.
281281
Generate images without having a window appear
282282
----------------------------------------------
283283

284-
Simply do not call `~matplotlib.pyplot.show`, and directly save the figure to
285-
the desired format::
284+
The recommended approach since matplotlib 3.1 is to explicitly create a Figure
285+
instance::
286+
287+
from matplotlib.figure import Figure
288+
fig = Figure()
289+
ax = fig.subplots()
290+
ax.plot([1, 2, 3])
291+
fig.savefig('myfig.png')
292+
293+
This prevents any interaction with GUI frameworks and the window manager.
294+
295+
It's alternatively still possible to use the pyplot interface. Instead of
296+
calling `matplotlib.pyplot.show`, call `matplotlib.pyplot.savefig`.
297+
298+
Additionally, you must ensure to close the figure after saving it. Not
299+
closing the figure is a memory leak, because pyplot keeps references
300+
to all not-yet-shown figures::
286301

287302
import matplotlib.pyplot as plt
288303
plt.plot([1, 2, 3])

0 commit comments

Comments
 (0)