I am using Linux server to set up a django project. I got this error: \"Failed to create /var/www/.matplotlib; consider setting MPLCONFIGDIR to a writable directory for matp
Set the MPLCONFIGDIR in code before you import matplotlib. Make sure the directory has permissions such that it can be written to by the app.
import os
os.environ['MPLCONFIGDIR'] = "/home/lab/website/graph"
import matplotlib
Alternatively, you could set it to a tempfile.
import os
import tempfile
os.environ['MPLCONFIGDIR'] = tempfile.mkdtemp()
import matplotlib
If you happen to be working on an AWS Lambda, like I was when I came looking for answers to this, use the /tmp folder:
import os
os.environ['MPLCONFIGDIR'] = "/tmp"
import matplotlib
Per @Esteban I do something like this in modules or scripts:
import os
try:
import matplotlib
except:
import tempfile
import atexit
import shutil
mpldir = tempfile.mkdtemp()
atexit.register(shutil.rmtree, mpldir) # rm directory on succ exit
os.environ['MPLCONFIGDIR'] = mpldir
import matplotlib
This way the temporary directory is removed on exit.