成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

用 Python 將 matplotlib 圖表集成到 PDF 中

開發 后端
在本指南中,我們將使用 borb —— 一個專門用于閱讀、操作和生成 PDF 文檔的 Python 庫。

Python中文社區(ID:python-china) 

介紹

PDF 格式是與平臺無關,它獨立于底層操作系統和渲染引擎。事實上,PDF 是基于一種腳本語言——PostScript,它是第一個獨立于設備的頁面描述語言。

在本指南中,我們將使用 borb —— 一個專門用于閱讀、操作和生成 PDF 文檔的 Python 庫。它提供了一個低級模型(允許您訪問精確的坐標和布局)和一個高級模型(您可以將邊距、位置等精確計算委托給布局管理器) .

matplotlib 是一個數據可視化庫,也是許多其他流行庫(如 Seaborn)背后的引擎。

基于用于創建報告(通常包括圖形)的常見 PDF 文檔,我們將看看如何使用 borb 將 Matplotlib 圖表集成到 PDF 文檔中。

安裝 borb和 matplotlib

borb 可以從 GitHub 上的源代碼下載,或通過 pip 安裝:

  1. $ pip install borb 

matplotlib 也可以通過 pip 安裝: 

  1. $ pip install matplotlib

用 Borb 在 PDF 文檔中集成 Matplotlib 圖表

在創建餅圖等圖表之前,我們將編寫一個小的效用函數,該函數生成 N 種顏色,均勻分布在顏色光譜中。

每當我們需要創建繪圖并為每個部分著色時,這將對我們有所幫助: 

  1. from borb.pdf.canvas.color.color import HSVColor, HexColor  
  2. from decimal import Decimal  
  3. import typing  
  4. def create_n_colors(n: int) -> typing.List[str]:  
  5.   # The base color is borb-blue  
  6.   base_hsv_color: HSVColorHSVColor = HSVColor.from_rgb(HexColor("56cbf9"))  
  7.   # This array comprehension creates n HSVColor objects, transforms then to RGB, and then returns their hex string  
  8.   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 年代設計的,目的是更接近人類視覺感知色彩屬性的方式。在這些模型中,每種色調的顏色都排列在一個徑向切片中,圍繞中性色的中心軸,范圍從底部的黑色到頂部的白色:

[[430888]] 

用它表示顏色的優點是我們可以輕松地將顏色光譜分成相等的部分。

現在我們可以定義一個 create_pie_chart() 函數(或其他類型圖的函數): 

  1. # New import(s)  
  2. import matplotlib.pyplot as plt  
  3. from borb.pdf.canvas.layout.image.chart import Chart  
  4. from borb.pdf.canvas.layout.layout_element import Alignment  
  5. def create_piechart(labels: typing.List[str], data: typing.List[float]):  
  6.   # Symetric figure to ensure equal aspect ratio  
  7.   fig1, ax1 = plt.subplots(figsize=(4, 4))  
  8.   ax1.pie(  
  9.     data,  
  10.     explode=[0 for _ in range(0, len(labels))],  
  11.     labelslabels=labels,  
  12.     autopct="%1.1f%%" 
  13.     shadow=True 
  14.     startangle=90 
  15.     colors=create_n_colors(len(labels)),  
  16.   )  
  17.   ax1.axis("equal")  # Equal aspect ratio ensures that pie is drawn as a circle.  
  18.   return Chart(  
  19.     plt.gcf(),  
  20.     width=Decimal(200),  
  21.     height=Decimal(200),  
  22.     horizontal_alignment=Alignment.CENTERED,  
  23.   ) 

在這里,我們使用 Matplotlib 通過 pie() 函數創建餅圖。

PyPlot 實例的 gcf() 函數返回當前圖形。該圖可以嵌入到 PDF 文檔中,方法是將其注入到 Chart 構造函數中,并與您的自定義參數(例如width, height 和 horizontal_alignment)一起插入。

您只需向Chart構造函數提供一個 Matplotlib 圖。

將 Matplotlib 圖表添加到 PDF 文檔

現在是時候創建我們的 PDF 文檔并向其中添加內容了。 

  1. # New import(s)  
  2. from borb.pdf.document import Document  
  3. from borb.pdf.page.page import Page  
  4. from borb.pdf.pdf import PDF  
  5. from borb.pdf.canvas.layout.page_layout.multi_column_layout import MultiColumnLayout  
  6. from borb.pdf.canvas.layout.page_layout.page_layout import PageLayout  
  7. from borb.pdf.canvas.layout.text.paragraph import Paragraph  
  8. # Create empty Document  
  9. pdf = Document()  
  10. # Create empty Page  
  11. page = Page()  
  12. # Add Page to Document  
  13. pdf.append_page(page)  
  14. # Create PageLayout  
  15. layout: PageLayout = MultiColumnLayout(page) 
  16. # Write title  
  17. layout.add(Paragraph("About Lorem Ipsum",   
  18.                      font_size=Decimal(20),   
  19.                      font="Helvetica-Bold")) 

我們將在此 PDF 中使用連字符,以確保文本的布局更加流暢。borb 中的連字符非常簡單: 

  1. # New import(s)  
  2. from borb.pdf.canvas.layout.hyphenation.hyphenation import Hyphenation  
  3. # Create hyphenation algorithm  
  4. hyphenation_algorithm: HyphenationHyphenation = Hyphenation("en-gb")  
  5. # Write paragraph  
  6. layout.add(Paragraph(  
  7.     """  
  8.     Lorem Ipsum is simply dummy text of the printing and typesetting industry.   
  9.     Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,  
  10.     when an unknown printer took a galley of type and scrambled it to make a type specimen book.   
  11.     It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.   
  12.     It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,   
  13.     and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.  
  14.     """, text_alignment=Alignment.JUSTIFIED, hyphenation=hyphenation_algorithm)) 

現在我們可以使用我們之前聲明的函數添加餅圖; 

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

接下來我們將編寫另外三個 Paragraph對象。其中一個將不僅僅表示引用(側面邊框,不同字體等)。 

  1. # Write paragraph  
  2. layout.add(Paragraph(  
  3.     """  
  4.     Contrary to popular belief, Lorem Ipsum is not simply random text.   
  5.     It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.   
  6.     Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words,   
  7.     consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature,   
  8.     discovered the undoubtable source.  
  9.     """, text_alignment=Alignment.JUSTIFIED, hyphenation=hyphenation_algorithm))  
  10. # Write paragraph  
  11. layout.add(Paragraph(  
  12.     """  
  13.     Lorem Ipsum is simply dummy text of the printing and typesetting industry.   
  14.     """,   
  15.     font="Courier-Bold" 
  16.     text_alignment=Alignment.JUSTIFIED,   
  17.     hyphenation=hyphenation_algorithm 
  18.     border_color=HexColor("56cbf9"), 
  19.     border_width=Decimal(3),  
  20.     border_left=True 
  21.     padding_left=Decimal(5),  
  22.     padding_bottom=Decimal(5),  
  23. ))  
  24. # Write paragraph  
  25. layout.add(Paragraph(  
  26.     """  
  27.     Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"  
  28.     (The Extremes of Good and Evil) by Cicero, written in 45 BC.   
  29.     This book is a treatise on the theory of ethics, very popular during the Renaissance.  
  30.     """, text_alignment=Alignment.JUSTIFIED, hyphenation=hyphenation_algorithm)) 

讓我們添加另一個繪圖。 

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

還有一段內容(Paragraph): 

  1. # Write paragraph  
  2. layout.add(Paragraph(  
  3.     """  
  4.     It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.  
  5.     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',   
  6.     making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text,   
  7.     and a search for 'lorem ipsum' will uncover many web sites still in their infancy.   
  8.     Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).  
  9.     """, text_alignment=Alignment.JUSTIFIED, hyphenation=hyphenation_algorithm)) 

最后,我們可以存儲文檔(Document): 

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

運行此代碼會生成如下所示的 PDF 文檔:

 

 

在本文中,您學習了如何使用 borb 將 Matplotlib 圖表集成到 PDF 。 

 

 

責任編輯:龐桂玉 來源: Python中文社區
相關推薦

2010-02-24 15:25:41

ibmdwGooglePHP

2022-12-01 17:13:44

2009-04-01 10:38:00

RFID Web服務

2012-10-11 17:01:08

IBMdw

2020-09-17 16:00:03

Python 開發編程語言

2022-03-24 07:44:41

OPA安全策略Rego

2012-11-01 11:34:31

IBMdw

2021-04-01 15:42:45

人工智能軟件測試

2011-09-02 14:05:57

云計算解決方案虛擬化

2021-12-08 16:49:19

CICD

2022-07-13 15:54:14

Matplotlib圖表

2018-07-11 11:26:55

2023-06-26 14:03:31

2023-03-07 11:42:38

ChatGPT開發工具

2021-05-10 15:14:23

Python棒棒糖圖表

2011-07-11 16:10:38

SQL移植Oracle數據庫

2011-07-11 16:47:57

數據庫移植SQL ServerOracle

2011-07-11 15:23:37

Sql DevelopOracle Migr

2020-05-11 10:59:02

PythonWord工具

2011-07-11 18:22:34

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 天天综合天天 | 91视频免费视频 | 亚洲成人高清 | 久久9久 | 欧美vide | 国产免费一区二区 | 噜久寡妇噜噜久久寡妇 | 在线免费av电影 | 精品中文字幕一区 | 亚洲精品国产精品国自产在线 | 完全免费在线视频 | 午夜视频在线视频 | 中文字幕日韩欧美一区二区三区 | 91免费电影| 亚洲精品一区二区在线观看 | 91看片在线观看 | 国户精品久久久久久久久久久不卡 | 人人擦人人 | 中文字幕日本一区二区 | 天天综合网天天综合色 | 欧美一级电影免费 | 亚洲二区视频 | 亚洲资源在线 | 久久精点视频 | 国产精品爱久久久久久久 | 亚洲一区二区三区免费在线观看 | 99精品国产一区二区三区 | av天天爽| h视频免费观看 | 国产日产精品一区二区三区四区 | 欧美美乳| 精品一级 | 91中文字幕在线 | 日批av| 国产一区二区三区四区在线观看 | 亚洲毛片| 亚洲成人综合社区 | 亚洲精品区| 成人欧美一区二区三区黑人孕妇 | 国产在线一区二区 | 91观看|