使用PdfPages添加文本 - matplotlib

时间:2018-03-23 06:55:36

标签: python pdf matplotlib text pdfpages

在这个example官方文档之后,我可以创建一个pdf文件,其中包含我想要的不同页面中的图表。但我想在页面中添加一些文字(不在剧情内),我尝试过这种方式但没有成功:

with PdfPages('multipage_pdf.pdf') as pdf:
    fig = plt.figure(figsize=(11.69,8.27))
    x = df1.index
    y1 = df1[col1]
    y2 = df1[col2]
    plt.plot(x, y1, label=col1)
    plt.plot(x, y2, label=col2)
    plt.legend(loc='best')
    plt.grid(True)
    plt.title('Title')
    txt = 'this is an example'
    plt.text(1,1,txt)
    pdf.savefig()
    plt.close()

如何显示文字this is an example? 是否可以创建仅包含文本的第一页? 提前致谢

1 个答案:

答案 0 :(得分:6)

文本'this is an example'位于数据坐标中的(1,1)位置。如果您的数据范围不同,则可能不在图中。在图形坐标中指定它是有意义的。范围从0到1,其中0,0是左下角,1,1是右上角。 E.g。

plt.text(0.05,0.95,txt, transform=fig.transFigure, size=24)

这个例子

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

with PdfPages('multipage_pdf.pdf') as pdf:
    fig = plt.figure(figsize=(11.69,8.27))
    plt.plot([1,2,3], [1,3,2], label="col1")
    plt.plot([1,2,3],  [2,1,3], label="col2")
    plt.legend(loc='best')
    plt.grid(True)
    plt.title('Title')
    txt = 'this is an example'
    plt.text(0.05,0.95,txt, transform=fig.transFigure, size=24)
    pdf.savefig()
    plt.close()

创建此情节

enter image description here

您无法创建空的pdf页面。但是,当然你可以通过创建一个没有内容的数字,或者只是文本的空图来模仿一个。

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

with PdfPages('multipage_pdf.pdf') as pdf:
    firstPage = plt.figure(figsize=(11.69,8.27))
    firstPage.clf()
    txt = 'This is the title page'
    firstPage.text(0.5,0.5,txt, transform=firstPage.transFigure, size=24, ha="center")
    pdf.savefig()
    plt.close()

    fig = plt.figure(figsize=(11.69,8.27))
    plt.plot([1,2,3], [1,3,2], label="col1")
    plt.plot([1,2,3],  [2,1,3], label="col2")
    plt.legend(loc='best')
    plt.grid(True)
    plt.title('Title')
    txt = 'this is an example'
    plt.text(0.05,0.95,txt, transform=fig.transFigure, size=24)
    pdf.savefig()
    plt.close()

enter image description here