Matplotlib:如何将图保存为pdf文件

时间:2018-09-27 08:48:53

标签: python matplotlib

该问题的各种变体已经得到了回答,但在我的情况下,没有任何答案有效。我能得到的最好的是一个空白的pdf表格或一个损坏的文件。

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())

2 个答案:

答案 0 :(得分:2)

删除plt.show(),因为它也可以清除数字。

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')

答案 1 :(得分:0)

这对我有用

def binarysearch(A, v, x, y):
    found = True
    while found:
        if x < y:
            h = (x+y) //2
            if A[h] < v:
                x = h+1  // replaced
            else:
                y = h    // replaced
        elif A[x] == v:
            found = False
            print("Element you are looking for is at index {}".format(x))
        else:
            found = False
            print("Value is not in array")