Embed in a web application server (Flask)
When using Matplotlib in a web server it is strongly recommended to not use
pyplot (pyplot maintains references to the opened figures to make
show work, but this will cause memory leaks unless the
figures are properly closed).
Since Matplotlib 3.1, one can directly create figures using the Figure
constructor and save them to in-memory buffers. In older versions, it was
necessary to explicitly instantiate an Agg canvas (see e.g.
CanvasAgg demo).
The following example uses Flask, but other frameworks work similarly: