Using matplotlib without installing Tkinter GUI framework

By xngo on March 2, 2019


Most of the matplotlib examples found on the Internet assume that Tkinter GUI framework is installed on your computer. However, it is not installed on my computer. Without this framework, on the statement, it will throw the following error:

ImportError: No module named '_tkinter', please install the python3-tk package

To avoid this error, simply save the result in an image file. You simply need to call matplotlib.use('Agg') directive before importing pylab or pyplot. This will instruct matplotlib to use Agg backend, which makes nice PNGs using the C++ Anti-Grain rendering engine.

Example to avoid installing Tkinter framework

import matplotlib
matplotlib.use('Agg') # Bypass the need to install Tkinter GUI framework
import matplotlib.pyplot as plt
# You data points.
x = [1,  2, 3, 4]
y = [10, 3, 4, 5]
# Plot your data points.
plt.plot(x,y, label='Label Title!')
# Set graph labels & legend
plt.title('Interesting Graph\nCheck it out')
# Save graph to file.


Matplotlib screenshot of file saved

About the author

Xuan Ngo is the founder of He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.