Serafeim Serafeim - 6 months ago 29
Python Question

Using matplotlib *without* TCL

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' withoutt using TCL \o/

Answer

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?.

Comments