0

Here's a dummy script that makes three plots and saves them to PDF.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({"A":np.random.normal(100),
                   "B":np.random.chisquare(5, size = 100),
                   "C":np.random.gamma(5,size = 100)})

for i in df.columns:
    plt.hist(df[i])
    plt.savefig(i+".pdf", format = "pdf")
    plt.close()

I'm using spyder, which uses IPython. When I run this script, three windows pop at me and then go away. It works, but it's a little annoying.

How can I make the figures get saved to pdf without ever being rendered on my screen?

I'm looking for something like R's

pdf("path/to/plot/name.pdf")
commands
dev.off()

inasmuch as nothing gets rendered on the screen, but the pdf gets saved.

generic_user
  • 3,430
  • 3
  • 32
  • 56
  • Possible duplicate of https://stackoverflow.com/questions/15713279/calling-pylab-savefig-without-display-in-ipython – trsvchn Feb 26 '19 at 21:46

2 Answers2

2

Aha. Partially based on the duplicate suggestion (which wasn't exactly a duplicate), this works:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({"A":np.random.normal(100),
                   "B":np.random.chisquare(5, size = 100),
                   "C":np.random.gamma(5,size = 100)})

import matplotlib
old_backend = matplotlib.get_backend()
matplotlib.use("pdf")

for i in df.columns:
    plt.hist(df[i])
    plt.savefig(i+".pdf", format = "pdf")
    plt.close()

matplotlib.use(old_backend)

Basically, set the backend to something like a pdf device, and then set it back to whatever you're accustomed to.

generic_user
  • 3,430
  • 3
  • 32
  • 56
1

I am referring you to this StackOverflow answer which cites this article as an answer. In the SO answer they also suggest plt.ioff() but are concerned that it could disable other functionality should you want it.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Matt Cuffaro
  • 153
  • 3
  • 8