syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Python Matplotlib how do I plot to image with no pop-up window?

I recently encountered a use-case asking me to plot data to several images from a script.

The default behavior of Matplotlib is to display a pop-up window when I ask the API for a plot.

Then the script stops.

This behavior is inconvenient if I want to plot data to several images from a single script.

The line of syntax I use to work-around this behavior usually resides early in the script:
# /a/ks/b/python/matplotlib_use_agg.py

# In Python Matplotlib how do I plot to image with no pop-up window?

import matplotlib
# The next line prevents pop-up from halting the script after first plot:
matplotlib.use('Agg')
import matplotlib.pyplot as plt

xvals = [1.1, 1.2, 2.2]
yvals = [1.4, 1.2, 2.2]
plt.plot(xvals, yvals)
plt.savefig('/tmp/myplot1')
plt.close

plt.plot(xvals, yvals)
plt.savefig('/tmp/myplot2')
plt.close

plt.plot(xvals, yvals)
plt.savefig('/tmp/myplot3')
plt.close



syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me