Matplotlib in Django "Starting a Matplotlib GUI outside of the main thread..."

Hi everyone,

Just a quick question. I’ve done an application with a Matplotlib chart. When I start the app and display the first chart, I got the warning message “Starting a Matplotlib GUI outside of the main thread will likely fail.”.

I just wanted to check if that message is normal or if it requires an action to prevent any potential later issue. I’ve done nothing special. Just a view rendering a chart.

Thank you,

A bit of a guess here, but my first reaction to this is that as long as you don’t use any of the interactive elements within the pyplot module, you should be ok.

I might also try configuring it to use a non-interactive backend (See Backends — Matplotlib 3.5.2 documentation). That may eliminate the message.

I had the same error when messing with matplotlib. Pls post again if Kens post solves it

Hi !

I got rid of these warnings by setting Agg or SVG as “renderer” (if I can say this).
It can be done with :

import matplotlib

That’s all I got. But now, I have issues because when the app receives a lot of request, Matplotlib sometimes generates wrong charts (missing points or lines, wrong data inputed…).
I’m beginning to wonder if Matplotlib is a good choice for a web application…

My first question on this is whether or not there may be any kind of concurrent access going on between multiple requests.

From the docs at How-to — Matplotlib 3.5.2 documentation

Matplotlib is not thread-safe: in fact, there are known race conditions that affect certain artists.

If this is a shared resource where multiple people can access it at the same time, you’re going to need to manage that access. (There are a couple different ways to do it, each with their own advantages / disadvantages.)

Even if the requests aren’t truly concurrent, I’d be concerned about the housekeeping involved between requests.

(And no, I would not think that Matplotlib is a good choice for an interactive web application.)

The question is then, what is?

I guess that really depends upon what your fundamental objectives are.

I know a lot of people that use either D3 or Chart.js.

I don’t do a lot of it, so I’m not particularly knowledgeable of all the specifics. I did help someone once set up a Matplotlib background task controlled by Celery, where the Celery task started a new process for each graph needing to be plotted. (That’s how/when I learned about the threading issues and non-interactive backends - but that was almost 7 years ago now. My memory on that’s a bit hazy.)

Seems to work just fine :grin:
Thank you for explaining :clap: