8

Various variants of this question have already been answered but none of the answers is working in my case. The best I can get is an empty pdf sheet, or a corrupted file.

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np

def getdata():
    return np.random.uniform(0,1,10)

fig, axe = plt.subplots(5, 2)
row=[0,0,1,1,2,2,3,3,4,4]
col=[0,1,0,1,0,1,0,1,0,1]
for im in range(10):
    r=row[im]
    c=col[im]
    axe[r][c].scatter(getdata(), getdata())
plt.show()

# trial 1 -> generates a blank page
plt.savefig('figure1.pdf')

# trial 2 -> generates a corrupted pdf file
pdf=PdfPages('figure2.pdf')
pdf.savefig(plt.gcf())
quickbug
  • 4,708
  • 5
  • 17
  • 21

2 Answers2

8

Remove plt.show(), as it also clears the figure.

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

def getdata():
    return np.random.uniform(0,1,10)

fig, axe = plt.subplots(5, 2)
row=[0,0,1,1,2,2,3,3,4,4]
col=[0,1,0,1,0,1,0,1,0,1]
for im in range(10):
    r=row[im]
    c=col[im]
    axe[r][c].scatter(getdata(), getdata())

# trial 1 -> tried and it works, no need for trial 2
plt.savefig('figure1.pdf')
Piotrek
  • 1,400
  • 9
  • 16
  • 2
    Thanks to Piotrek. plt.show() closes the figure and opens a new one. I therefore had to put the plt.show() command at the very end of the code (or at least when I will not use the figure any longer) – quickbug Sep 27 '18 at 09:42
1

This works for me

saveas(gcf,'myfigure.pdf')
user3376851
  • 149
  • 10