使用 PdfPages 添加文本 - matplotlib

Add text with PdfPages - matplotlib

按照官方文档的 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? 是否也可以创建只有文本的第一页? 提前致谢

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

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

创建此情节

您不能创建空的 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()