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/
The last, Agg, is a non-interactive backend that can only write to files. It is used on Linux, if Matplotlib cannot connect to either an X display or a Wayland display.
If you are using Matplotlib from within a script, the function plt. show() is your friend. plt. show() starts an event loop, looks for all currently active figure objects, and opens one or more interactive windows that display your figure or figures.
(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.
(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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With