用 Python 将 matplotlib 图表集成到 PDF 中

2023-05-16

058226c16c1d7060e7f104d0e4ce44e9.png

介绍

PDF 格式是与平台无关,它独立于底层操作系统和渲染引擎。事实上,PDF 是基于一种脚本语言——PostScript,它是第一个独立于设备的页面描述语言。

在本指南中,我们将使用 borb —— 一个专门用于阅读、操作和生成 PDF 文档的 Python 库。它提供了一个低级模型(允许您访问精确的坐标和布局)和一个高级模型(您可以将边距、位置等精确计算委托给布局管理器) .

matplotlib 是一个数据可视化库,也是许多其他流行库(如 Seaborn)背后的引擎。

基于用于创建报告(通常包括图形)的常见 PDF 文档,我们将看看如何使用 borb 将 Matplotlib 图表集成到 PDF 文档中。

安装 borbmatplotlib

borb 可以从 GitHub 上的源代码下载,或通过 pip 安装:

$ pip install borb

matplotlib 也可以通过 pip 安装:

$ pip install matplotlib

用 Borb 在 PDF 文档中集成 Matplotlib 图表

在创建饼图等图表之前,我们将编写一个小的效用函数,该函数生成 N 种颜色,均匀分布在颜色光谱中。

每当我们需要创建绘图并为每个部分着色时,这将对我们有所帮助:

from borb.pdf.canvas.color.color import HSVColor, HexColor
from decimal import Decimal
import typing

def create_n_colors(n: int) -> typing.List[str]:
  # The base color is borb-blue
  base_hsv_color: HSVColor = HSVColor.from_rgb(HexColor("56cbf9"))
  # This array comprehension creates n HSVColor objects, transforms then to RGB, and then returns their hex string
  return [HSVColor(base_hsv_color.hue + Decimal(x / 360), Decimal(1), Decimal(1)).to_rgb().to_hex_string() for x in range(0, 360, int(360/n))]

HSL 和 HSV/HSB 是由计算机图形学研究人员在 1970 年代设计的,目的是更接近人类视觉感知色彩属性的方式。在这些模型中,每种色调的颜色都排列在一个径向切片中,围绕中性色的中心轴,范围从底部的黑色到顶部的白色:

b43ba383b9ff7ae1812396e4015acf0a.png

用它表示颜色的优点是我们可以轻松地将颜色光谱分成相等的部分。

现在我们可以定义一个 create_pie_chart() 函数(或其他类型图的函数):

# New import(s)
import matplotlib.pyplot as plt
from borb.pdf.canvas.layout.image.chart import Chart
from borb.pdf.canvas.layout.layout_element import Alignment

def create_piechart(labels: typing.List[str], data: typing.List[float]):

  # Symetric figure to ensure equal aspect ratio
  fig1, ax1 = plt.subplots(figsize=(4, 4))
  ax1.pie(
    data,
    explode=[0 for _ in range(0, len(labels))],
    labels=labels,
    autopct="%1.1f%%",
    shadow=True,
    startangle=90,
    colors=create_n_colors(len(labels)),
  )

  ax1.axis("equal")  # Equal aspect ratio ensures that pie is drawn as a circle.

  return Chart(
    plt.gcf(),
    width=Decimal(200),
    height=Decimal(200),
    horizontal_alignment=Alignment.CENTERED,
  )

在这里,我们使用 Matplotlib 通过 pie() 函数创建饼图。

PyPlot 实例的 gcf() 函数返回当前图形。该图可以嵌入到 PDF 文档中,方法是将其注入到 Chart 构造函数中,并与您的自定义参数(例如width, heighthorizontal_alignment)一起插入。

您只需向Chart构造函数提供一个 Matplotlib 图。

将 Matplotlib 图表添加到 PDF 文档

现在是时候创建我们的 PDF 文档并向其中添加内容了。

# New import(s)
from borb.pdf.document import Document
from borb.pdf.page.page import Page
from borb.pdf.pdf import PDF
from borb.pdf.canvas.layout.page_layout.multi_column_layout import MultiColumnLayout
from borb.pdf.canvas.layout.page_layout.page_layout import PageLayout
from borb.pdf.canvas.layout.text.paragraph import Paragraph

# Create empty Document
pdf = Document()

# Create empty Page
page = Page()

# Add Page to Document
pdf.append_page(page)

# Create PageLayout
layout: PageLayout = MultiColumnLayout(page)

# Write title
layout.add(Paragraph("About Lorem Ipsum", 
                     font_size=Decimal(20), 
                     font="Helvetica-Bold"))

我们将在此 PDF 中使用连字符,以确保文本的布局更加流畅。borb 中的连字符非常简单:

# New import(s)
from borb.pdf.canvas.layout.hyphenation.hyphenation import Hyphenation

# Create hyphenation algorithm
hyphenation_algorithm: Hyphenation = Hyphenation("en-gb")

# Write paragraph
layout.add(Paragraph(
    """
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
    Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
    when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. 
    It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, 
    and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    """, text_alignment=Alignment.JUSTIFIED, hyphenation=hyphenation_algorithm))

现在我们可以使用我们之前声明的函数添加饼图;

# Write graph
layout.add(create_piechart(["Loren", "Ipsum", "Dolor"], 
                           [0.6, 0.3, 0.1]))

接下来我们将编写另外三个 Paragraph对象。其中一个将不仅仅表示引用(侧面边框,不同字体等)。

# Write paragraph
layout.add(Paragraph(
    """
    Contrary to popular belief, Lorem Ipsum is not simply random text. 
    It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. 
    Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, 
    consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, 
    discovered the undoubtable source.
    """, text_alignment=Alignment.JUSTIFIED, hyphenation=hyphenation_algorithm))

# Write paragraph
layout.add(Paragraph(
    """
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
    """, 
    font="Courier-Bold",
    text_alignment=Alignment.JUSTIFIED, 
    hyphenation=hyphenation_algorithm,
    border_color=HexColor("56cbf9"),
    border_width=Decimal(3),
    border_left=True,
    padding_left=Decimal(5),
    padding_bottom=Decimal(5),
))

# Write paragraph
layout.add(Paragraph(
    """
    Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" 
    (The Extremes of Good and Evil) by Cicero, written in 45 BC. 
    This book is a treatise on the theory of ethics, very popular during the Renaissance.
    """, text_alignment=Alignment.JUSTIFIED, hyphenation=hyphenation_algorithm))

让我们添加另一个绘图。

# Write graph
layout.add(create_piechart(["Loren", "Ipsum", "Dolor", "Sit", "Amet"], 
                           [600, 30, 89, 100, 203]))

还有一段内容(Paragraph):

# Write paragraph
layout.add(Paragraph(
    """
    It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. 
    The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', 
    making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, 
    and a search for 'lorem ipsum' will uncover many web sites still in their infancy. 
    Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
    """, text_alignment=Alignment.JUSTIFIED, hyphenation=hyphenation_algorithm))

最后,我们可以存储文档(Document):

# Write to disk
with open("output.pdf", "wb") as pdf_file_handle:
  PDF.dumps(pdf_file_handle, pdf)

运行此代码会生成如下所示的 PDF 文档:

d33fde226ce53b96b2945b0ce33547a7.png

在本文中,您学习了如何使用 borb 将 Matplotlib 图表集成到 PDF 。 

ae6f0441fb1997c4b7ead89b7401f7b8.gif458e5c72dc3a3b903aa51e14e7d2b51a.gif287463cf17a9795677d46545124384a2.gif

47cee409432ab7dbb0a2de6efa539801.png

3e79aa150a652df18e652a535aea900b.png

点击下方阅读原文加入社区会员

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用 Python 将 matplotlib 图表集成到 PDF 中 的相关文章

随机推荐

  • libpng warning: iCCP: known incorrect sRGB profile 报错

    libpng warning iCCP known incorrect sRGB profile 警告 xff0c 问题解决 目录 libpng warning iCCP known incorrect sRGB profile 警告 xf
  • 卷积神经网络核心概念再复习+Pytorch一维卷积的实现

    蓝色 紫色 红色 深度学习之卷积神经网络 基本的图像分类模型架构 卷积层 xff1a 用来提取图像的底层特征 池化层 xff1a 防止过拟合 xff0c 减小数据维度 全连接层 xff1a 汇总卷积层和池化层得到的底层特征和信息 xff0c
  • Ubuntu20.04安装过程 【磁盘分区】

    前言 首先 要了解你的电脑配置 xff08 我实验室的如下 xff09 xff1a 整个安装Ubuntu系统的过程大致如下 xff1a 华硕主板按F2 F8 xff0c 这个可以百度 也可以重新启动 xff0c 在你的第一个界面上能看到 按
  • KLT光流跟踪特征点对

    前言 本篇所述为KLT光流跟踪两个视频中匹配特征点对的具体实现 61 gt 源码见Github openCV版本 xff1a 4 5 5 函数详解 1 特征提取 1 SIFT特征提取调用方式 sift span class token op
  • Ubuntu 20.04桌面文件夹图标消失及文件系统无法打开

    前言 之前遇到过服务器上桌面图标突然消失的情况 在更换系统语言之后 xff0c 桌面出现过一次这种情况 xff0c 经过重启之后就恢复了 再后来又莫名其妙出现了这么个问题 xff0c 最开始搜索的解决方案是 让你打开任务管理器 gnome
  • 【论文笔记】Deblur-NeRF == HKU ==CVPR‘2022

    蓝色 紫色 红色 Deblur NeRF Neural Radiance Fields from Blurry Images Author From Abstract 神经辐射场 xff08 NeRF xff09 由于其显著的合成质量 xf
  • Linux安装 metashape

    1 下载软件 3D三维建模软件 Agisoft Metashape Pro 2 安装 span class token comment 进入root模式 xff0c 如果之前没有设置过密码 span span class token fun
  • Information Collection

    港澳新地区 香港理工大学 杨波 助理教授 vLAR实验室 欧洲 ETH Z rich Marc Pollefeys Computer Vision and Geometry Group TU Delft 3D geoinformation
  • 804半导体物理 中科院半导体所考研经验

    本人2021考研 xff0c 半导体研究所 xff0c 物理电子学 xff0c 数一英语一 xff0c 专业课804半导体 自己之前在备考的时候就感觉专业课的资料和备考经验比较少 xff0c 现在就写一些自己总结的经验 xff0c 放一些资
  • 一些cmake error fixed

    建完虚拟环境后 运行 pip install 出现报错 xff0c 显示svox2安装出错 xff0c 然后开始进入到svox2中进行手动编译和安装 1 cmake svox2 csrc pybind11找不到 conda span cla
  • metashape-pro python scripts render specified viewpoint

    官方python脚本使用文档 主函数 xff1a render 61 chunk model renderImage 1 实现特定视角的渲染需要通过脚本方式进行 xff0c 原本的metashape pro中是没有这个功能的 首先在meta
  • 【mega-nerf】调包失败&pip install失败解决方案

    Problem 1 调包失败 在这样的层级架构里调包 xff0c 输出无法找到 mega nerf 直接用 sys path append 没有作用 span class token comment import sys span span
  • 使用 rust 开发 stm32:前言

    更多分享内容可访问我的个人博客 https www niuiic top 本系列教程全部置于stm32专栏 本文为使用 rust 开发 stm32 系列教程前言 Why Rust Rust 特性就不用多介绍了 xff0c 有个编译器管着有时
  • docker与virtualbox切换使用

    管理员模式打开cmd 查看hyper v状态 xff1a bcdedit span class token operator span findstr hyperv 若状态显示 hypervisorlaunchtype Auto 则当前可支
  • 内存管理学习

    简单的内存分配算法学习 系统中一块剩余不用的大块连续内存 当需要分配内存块时 xff0c 将从这个大的内存块上分割出相匹配的内存块 xff0c 每个内存块都包含一个管理用的数据头 xff0c 通过这个头把使用块与空闲块用双向链表的方式链接起
  • 模拟I2C

    I2C具体内容参考资料 https blog csdn net sternlycore article details 85600668 https blog csdn net qq 43460068 article details 122
  • 巴特沃斯滤波器使用-butter

    matlab的函数butter 低通滤波使用方法 span class token punctuation span B A span class token punctuation span span class token operat
  • 单片机中uid的使用方法

    uid xff1a unique ID 每个单片机芯片出厂后唯一的ID xff0c 不会重复 uid有很多用途 xff0c 我们可以用来作为mac地址 xff0c 可以用来记录唯一的日志 xff0c 也可以用来防止固件被拷贝使用 本文所描述
  • c/c++单个文件或函数优化级别设置

    span class token macro property span class token directive hash span span class token directive keyword pragma span span
  • 用 Python 将 matplotlib 图表集成到 PDF 中

    介绍 PDF 格式是与平台无关 xff0c 它独立于底层操作系统和渲染引擎 事实上 xff0c PDF 是基于一种脚本语言 PostScript xff0c 它是第一个独立于设备的页面描述语言 在本指南中 xff0c 我们将使用 borb