Forums

Matplotlib in Django

I am trying to create plots with matplotlib and show them in my django app. I 'plotted' the plot to a BytesIO 'file' using plt.savefig(), which I then converted to base64 and then passed that string to my template. This was working fine in the default Django 1.10 (Python 2.7) environment.

I created a virtualenv for Django 1.11 (I wanted a feature that's new to Django 1.11), and then I encountered a problem with this process.

I got this error;

TclError at ..... no display name and no $DISPLAY environment variable

I tried setting this variable manualy in a few different ways (without any sucess) including using;

os.environ

Is there something that the default environment (Django 1.10, Python 2.7) has set up that mitigates this issue, that I'm not aware of?

It looks like something in your code is trying to draw to a display that doesn't exist on PythonAnywhere - because there aren't any. You probably need to select a backend explicitly with a matplotlib instance that you installed yourself: http://help.pythonanywhere.com/pages/MatplotLibGraphs/

I tried using

matplotlib.use("Agg")

as you have it on that page. I'm just curious why it would work on your instalation, and just not on my virtualenv....

Because we set up the PythonAnywhere installation to default to a non-screen based backend. The default for a matplotlib install is screen-based.

So how does one adjust that on his own?

Ultimately - I just switched over to your Python 3.6 Django 1.11 option, and it worked fine...

That's odd -- do you mean your code is working fine using Django 1.11 and Python 3.6, without the matplotlib.use("Agg")?