Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: how to save a plot in a pdf file [duplicate]

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())
like image 945
quickbug Avatar asked Apr 24 '26 07:04

quickbug


2 Answers

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')
like image 63
Piotrek Avatar answered Apr 26 '26 19:04

Piotrek


This works for me

saveas(gcf,'myfigure.pdf')
like image 38
user3376851 Avatar answered Apr 26 '26 19:04

user3376851



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!