chriswhite
chriswhite

Reputation: 1400

Python Saving PNG in Terminal vs IPython Notebook

I am writing a basic Python module which contains a function that plots some data from a Pandas DataFrame. The problem is that I expect users to call this function from both the interactive shell and IPython notebooks. Unfortunately, our interactive shell environment does not have any valid DISPLAY options for matplotlib to use, so I want my function (or the full module) to behave slightly different depending on which environment it is loaded into. (E.g., the default is show the plot without saving in IPython, and save the plot without showing in the shell).

This question gives me a partial answer, in that I can explicitly tell users to write matplotlib.use('Agg') before they ever import my module, but surely there is a more automated backend way to handle this?

Upvotes: 1

Views: 79

Answers (1)

szym
szym

Reputation: 5846

You could try checking if you are running into the situation (empty $DISPLAY) and default users to the Agg backend, rather than asking them to do so.

def configure_matplotlib():
   import os
   if 'DISPLAY' not in os.environ:
      if matplotlib.get_backend() != 'Agg':
          matplotlib.use('Agg')


import matplotlib
configure_matplotlib()
import matplotlib.pyplot as plt
...

Now matplotlib.use has no effect once pyplot has been imported, but if your users have already done so, they probably have a working configuration anyway.

Upvotes: 1

Related Questions