web-dev-qa-db-fra.com

Appel de pylab.savefig sans affichage dans ipython

Je dois créer une figure dans un fichier sans l'afficher dans le cahier IPython. Je ne suis pas clair sur l'interaction entre IPython et matplotlib.pylab À cet égard. Mais, lorsque j'appelle pylab.savefig("test.png"), le chiffre actuel est affiché en plus d'être enregistré dans test.png. Lors de l'automatisation de la création d'un grand ensemble de fichiers de tracé, cela est souvent indésirable. Ou dans le cas où un fichier intermédiaire pour le traitement externe par une autre application est souhaité.

Pas sûr qu'il s'agisse d'une question de cahier matplotlib ou IPython.

77
tnt

C'est une question matplotlib, et vous pouvez y remédier en utilisant un backend qui ne s'affiche pas pour l'utilisateur, par exemple. 'Agg':

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.plot([1,2,3])
plt.savefig('/tmp/test.png')

EDIT: Si vous ne voulez pas perdre la possibilité d'afficher des tracés, désactivez mode interactif , et appelez uniquement plt.show() lorsque vous êtes prêt à afficher les tracés:

import matplotlib.pyplot as plt

# Turn interactive plotting off
plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')

# Display all "open" (non-closed) figures
plt.show()
133
staticfloat

Nous n'avons pas besoin de plt.ioff() ou plt.show() (si nous utilisons %matplotlib inline). Vous pouvez tester le code ci-dessus sans plt.ioff(). plt.close() a le rôle essentiel. Essaye celui-là:

%matplotlib inline
import pylab as plt

# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')

Si vous exécutez ce code dans iPython, il affichera un deuxième tracé et si vous ajoutez plt.close(fig2) à la fin, vous ne verrez rien.

En conclusion Si vous fermez la figure par plt.close(fig), elle ne sera pas affichée.

46
Mojtaba Khodadadi