如何在python中使用pdfpages生成垂直PDF

时间:2015-08-23 06:04:34

标签: python pdf matplotlib

我正在使用from matplotlib.backends.backend_pdf import PdfPages生成包含多个(子)图的PDF。

有没有办法控制生成的pdf的方向(水平/垂直)?我经常得到横向PDF

感谢

2 个答案:

答案 0 :(得分:3)

如果使用set_size_inches功能设置图形的大小,PDF应该自动成为您想要的形状:

from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

with PdfPages('portrait.pdf') as pdf:
    x = range(10)
    y = [y * 2 for y in x]

    plt.figure()
    plt.clf()
    plt.plot(x, y)
    plt.xlabel('x axis')
    plt.ylabel('y axis')
    figure = plt.gcf()
    figure.set_size_inches([7,10])
    pdf.savefig(figure)

如果您将尺寸更改为[10,7],您应该会看到方向自动切换。

savefig确实有定位设置,例如orientation='portrait'但我不认为这会产生任何影响。你可以尝试一下。

答案 1 :(得分:0)

以下对我有用:

with PdfPages('portrait.pdf') as pdf:
     pdf.savefig(fig, orientation='portrait')
     plt.close()