Using matplotlib *without* TCL
Asked Answered
H

1

7

Exactly what the title says. Is there a way to use the matplotlib library without installing TCL? Please don't tell me to bite the bullet and install TCL - I know how to do it but for my own (ok maybe silly) reasons I don't want to.

I don't care about displaying the plots, I only want to be able to output them in a png. I tried various things (using different backends etc) but matplotlib always wanted to find tcl to work :( Why is TCL so essential for matplotlib?

Also, please notice that I am using windows -- I have installed everything that could be required (numpy, pandas, matplotlib) using pip.

@gerrit's solution is the correct one (I was trying to change the backends but I was doing it after loading pyplot -- the important thing seems to be that you need to change the backend immediately after imporing matplotlib). Here's a small example using it:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

fig, ax = plt.subplots( nrows=1, ncols=1 )
ax.plot([0,1,2], [10,20,3])

fig.savefig('foo.png')
plt.close(fig)

This will output a file named 'foo.png' without using TCL \o/

Hufnagel answered 26/5, 2016 at 11:20 Comment(0)
A
16

Matplotlib 3.0 and newer

(Added to answer in October 2018)

Starting with Matplotlib 3, released on 19 September 2018, the problem described in the question should not occur. From the what's new part of the documentation:

The default backend no longer must be set as part of the build process. Instead, at run time, the builtin backends are tried in sequence until one of them imports.

Headless linux servers (identified by the DISPLAY env not being defined) will not select a GUI backend.

So, as long as you make sure DISPLAY is not defined, you should not run into any problems with the backend when running in a script on a headless Linux server.

Matplotlib 2.2 and older

(Original answer May 2016)

Immediately after loading matplotlib, enter

matplotlib.use('Agg')

Do this before loading pyplot, if at all.

By default, Matplotlib uses the TkAgg backend, which requires Tcl. If you don't want to display the plots, Agg is fine. Other alternatives include WX and QTAgg, but both require the installation of additional libraries.

Alternately, you can set this directive in your matplotlibrc file:

backend : Agg

For details, see the Matplotlib Usage FAQ on What is a backend?.

Amorette answered 26/5, 2016 at 11:50 Comment(1)
Yes it works ! I've updated my question with a small example of using your solution - thanks!Hufnagel

© 2022 - 2024 — McMap. All rights reserved.