Python 如何将 matplotlib 图表集成进到PDF 中

目录
  • 1.介绍
  • 2.安装 borb和 matplotlib
  • 3.将 Matplotlib 图表添加到 PDF 文档

1.介绍

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

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

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

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

2.安装 borb和 matplotlib

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 年代设计的,目的是更接近人类视觉感知色彩属性的方式。在这些模型中,每种色调的颜色都排列在一个径向切片中,围绕中性色的中心轴,范围从底部的黑色到顶部的白色:

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

现在我们可以定义一个 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, height 和 horizontal_alignment)一起插入。

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

3.将 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 文档:

到此这篇关于Python 如何将 matplotlib 图表集成进到PDF 中的文章就介绍到这了,更多相关 matplotlib 图表集成到 PDF 中内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python matplotlib seaborn绘图教程详解

    目录 一.seaborn概述 二.数据整理 01折线图 02柱形图 03直方图 三.绘图 01设定调色盘 02柱状图 03技术图 04点图 05箱型图 06小提琴图 一.seaborn概述 Seaborn是在matplotlib的基础上进行了更高级的API封装,从而使得作图更加容易,在大多数情况下使用seaborn就能做出很具有吸引力的图.详情请查阅官网:seaborn 二.数据整理 import seaborn as sns import numpy as np import matplotl

  • Python matplotlib plotly绘制图表详解

    目录 一.整理数据 二.折线图 三.散点图 四.饼图 五.柱形图 六.点图(设置多个go对象) 七.2D密度图 八.简单3D图 一.整理数据 以300部电影作为数据源 import pandas as pd cnboo=pd.read_excel("cnboNPPD1.xls") cnboo import seaborn as sns import numpy as np import matplotlib as mpl from matplotlib import pyplot as

  • 利用python库matplotlib绘制不同的图表

    目录 1.绘制简单曲线图 2.绘制单条曲线图 3.绘制多条曲线 4.绘制直方图 5.绘制散点图 1.绘制简单曲线图 思路:通过3个坐标点,绘制曲线 import matplotlib.pyplot as plt   plt.plot([1, 3, 5], [4, 8, 10]) # 横坐标:1,3,5,纵坐标:4,8,10 # 显示所画的图 plt.show()  运行效果如图: 2.绘制单条曲线图 思路:先通过linspace绘制一条直线,然后在-pi~pi之间定义100个元素 import

  • python必备库Matplotlib画图神器

    目录 1.安装方法 2.用好官网的例子 最简单的应用-折线图 添加注释的方法 柱状图-BarLabel 折线图之CSD 前言: Matplotlib 通常与 NumPy.Pandas 一起使用,是数据分析中不可或缺的重要工具之一. Matplotlib 是 Python 中类似 MATLAB 的绘图工具,如果您熟悉 MATLAB,那么可以很快的熟悉它.Matplotlib 提供了一套面向对象绘图的 API,它可以轻松地配合 Python GUI 工具包(比如 PyQt,WxPython.Tkin

  • Python 如何将 matplotlib 图表集成进到PDF 中

    目录 1.介绍 2.安装 borb和 matplotlib 3.将 Matplotlib 图表添加到 PDF 文档 1.介绍 PDF 格式是与平台无关,它独立于底层操作系统和渲染引擎.事实上,PDF 是基于一种脚本语言——PostScript,它是第一个独立于设备的页面描述语言. 在本指南中,我们将使用 borb —— 一个专门用于阅读.操作和生成 PDF 文档的 Python 库.它提供了一个低级模型(允许您访问精确的坐标和布局)和一个高级模型(您可以将边距.位置等精确计算委托给布局管理器)

  • Python 如何将 matplotlib 图表集成进到PDF 中

    目录 1.介绍 2.安装 borb和 matplotlib 3.将 Matplotlib 图表添加到 PDF 文档 1.介绍 PDF 格式是与平台无关,它独立于底层操作系统和渲染引擎.事实上,PDF 是基于一种脚本语言——PostScript,它是第一个独立于设备的页面描述语言. 在本指南中,我们将使用 borb —— 一个专门用于阅读.操作和生成 PDF 文档的 Python 库.它提供了一个低级模型(允许您访问精确的坐标和布局)和一个高级模型(您可以将边距.位置等精确计算委托给布局管理器)

  • python如何用matplotlib创建三维图表

    Matplotlib 最开始被设计为仅支持二维的图表.到 1.0 版本发布左右,一些三维图表的工具在二维展示的基础上被创建了出来,结果就是 Matplotlib 提供了一个方便的(同时也是有限的)的可用于三维数据可视化的一套工具.三维图表可以使用载入mplot3d工具包来激活,这个包会随着 Matplotlib 自动安装: from mpl_toolkits import mplot3d 一旦模块被导入,三维 axes 就可以像其他普通 axes 一样通过关键字参数projection='3d'

  • 使用python绘制常用的图表

    本文介绍如果使用python汇总常用的图表,与Excel的点选操作相比,用python绘制图表显得比较比较繁琐,尤其提现在对原始数据的处理上.但两者在绘制图表过程中的思路大致相同,Excel中能完成的工作python大多也能做到.为了更清晰的说明使用python绘制图表的过程,我们在汇总图表的代码中进行注解,说明每一行代码的具体作用.并在文章的最后给出了自定义字体和图表配色的对应表. 准备工作 import numpy as np import pandas as pd #导入图表库以进行图表绘

  • python xlsxwriter库生成图表的应用示例

    xlsxwriter可能用过的人并不是很多,不过使用后就会感觉,他的功能让你叹服,除了可以按要求生成你所需要的excel外 还可以加上很形象的各种图,比如柱状图.饼图.折线图等. xlsxwriter 基本用法,创建 xlsx 文件并添加数据 官方文档:http://xlsxwriter.readthedocs.org/ xlsxwriter 可以操作 xls 格式文件 注意:xlsxwriter 只能创建新文件,不可以修改原有文件.如果创建新文件时与原有文件同名,则会覆盖原有文件 Linux

  • Python干货:分享Python绘制六种可视化图表

    可视化图表,有相当多种,但常见的也就下面几种,其他比较复杂一点,大都也是基于如下几种进行组合,变换出来的.对于初学者来说,很容易被这官网上众多的图表类型给吓着了,由于种类太多,几种图表的绘制方法很有可能会混淆起来. 因此,在这里,我特地总结了六种常见的基本图表类型,你可以通过对比学习,打下坚实的基础. 01. 折线图 绘制折线图,如果你数据不是很多的话,画出来的图将是曲折状态,但一旦你的数据集大起来,比如下面我们的示例,有100个点,所以我们用肉眼看到的将是一条平滑的曲线. 这里我绘制三条线,只

  • python学习之matplotlib绘制散点图实例

    要绘制单个点,可使用函数scatter(),并向其传递一对x和y坐标,它将在指定位置绘制一个点: """使用scatter()绘制散点图""" import matplotlib.pyplot as plt plt.scatter(2, 4) plt.show() 下面来设置输出的样式:添加标题,给轴加上标签,并确保所有文本都大到能够看清.并使用scatter()绘制一系列点 """使用scatter()绘制散点图&

  • python 绘图模块matplotlib的使用简介

    上周对线上某几个磁盘进行了fio硬盘性能测试,测试完成之后的结果需要绘制成图像展示出来.我在官网上查找了一下fio自带的命令fio_generate_plot和fio2gnuplot工具的用法,找到了图像的绘制方法,在某一个单一的场景下,确实可以使用这两个工具来进行硬盘性能图像绘制,但是问题是,如果要对比多个场景下绘制出来的图像的差异,fio自带的绘图工具实现起来就有些困难了,但是确实也能实现.例如下图: 如图所示为磁盘iodepth不变,numjobs在(1,8,16)三种不同的场景下绘制出来

  • Python绘图库Matplotlib的基本用法

    一.前言 Matplotlib是Python的绘图库,不仅具备强大的绘图功能,还能够在很多平台上使用,和Jupyter Notebook有极强的兼容性. 二.线型图 import matplotlib.pyplot as plt import numpy as np # 指定生成随机数的种子,这样每次运行得到的随机数都是相同的 np.random.seed(42) # 生成30个满足平均值为0.方差为1的正态分布的样本 x = np.random.randn(30) # plot本意有"绘制(图

  • Python编程使用matplotlib挑钻石seaborn画图入门教程

    目录 scatter_plot lmplot jointplot 挑钻石第二弹 seaborn是matplotlib的补充包,提供了一系列高颜值的figure,并且集成了多种在线数据集,通过sns.load_dataset()进行调用,可供学习,如果网络不稳定,可下载到本地,然后在调用的时候使用把cache设为True. scatter_plot 官方的示例就很不错,绘制了diamonds数据集中的钻石数据.diamonds中总共包含十项数据,分别是重量/克拉.切割水平.颜色.透明度.深度.ta

随机推荐