加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

使用PdfPages添加文本 – matplotlib

发布时间:2020-12-20 11:03:15 所属栏目:Python 来源:网络整理
导读:在这个 example的官方文档之后,我可以在不同的页面中创建一个包含我想要的图的pdf文件.但是我想在页面中添加一些文本(不在图中)并且我已经尝试过这种方式而没有成功: with PdfPages('multipage_pdf.pdf') as pdf: fig = plt.figure(figsize=(11.69,8.27)) x
在这个 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()

我怎样才能显示文本这是一个例子?
是否可以创建仅包含文本的第一页?
提前致谢

解决方法

文本“这是一个例子”放在数据坐标中的位置(1,1).如果您的数据范围不同,则可能不在图中.在图形坐标中指定它是有意义的.范围从0到1,其中0,0是左下角,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,label="col2")
    plt.legend(loc='best')
    plt.grid(True)
    plt.title('Title')
    txt = 'this is an example'
    plt.text(0.05,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,transform=firstPage.transFigure,size=24,ha="center")
    pdf.savefig()
    plt.close()

    fig = plt.figure(figsize=(11.69,size=24)
    pdf.savefig()
    plt.close()

enter image description here

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读