In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, I would like to share with you how Python integrates the matplotlib chart into the PDF related knowledge points, detailed content, clear logic, I believe that most people still know too much about this knowledge, so share this article for your reference, hope that you have something to gain after reading this article, let's take a look at it.
1. Introduction
The PDF format is platform independent, independent of the underlying operating system and rendering engine. In fact, PDF is based on a scripting language, PostScript, which is the first device-independent page description language.
In this guide, we will use borb, a Python library dedicated to reading, manipulating, and generating PDF documents. It provides a low-level model (which allows you to access precise coordinates and layouts) and a high-level model (you can delegate precise calculations of margins, positions, and so on to the layout manager).
Matplotlib is a data visualization library and the engine behind many other popular libraries, such as Seaborn.
Based on the common PDF documents used to create reports (usually including graphics), we will look at how to use borb to integrate Matplotlib charts into PDF documents.
two。 Install borb and matplotlib
Borb can be downloaded from the source code on GitHub or installed through pip:
$pip install borb
Matplotlib can also be installed through pip:
$pip install matplotlib
Integrate Matplotlib diagrams into PDF documents with Borb
Before creating a chart such as a pie chart, we will write a small utility function that generates N colors that are evenly distributed in the color spectrum.
Whenever we need to create a drawing and color each part, this will help us:
From borb.pdf.canvas.color.color import HSVColor, HexColorfrom decimal import Decimalimport 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 (0360, int (360))]
HSL and HSV/HSB were designed by computer graphics researchers in the 1970s to be closer to the way human vision perceives color attributes. In these models, the colors of each tone are arranged in a radial slice, around the central axis of the neutral color, ranging from black at the bottom to white at the top:
The advantage of using it to represent color is that we can easily divide the color spectrum into equal parts.
Now we can define a create_pie_chart () function (or other type of graph function):
# New import (s) import matplotlib.pyplot as pltfrom borb.pdf.canvas.layout.image.chart import Chartfrom 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,)
Here, we use Matplotlib to create a pie chart through the pie () function.
The gcf () function of the PyPlot instance returns the current drawing. The diagram can be embedded in an PDF document by injecting it into the Chart constructor and inserting it with your custom parameters such as width, height, and horizontal_alignment.
We just need to provide a Matplotlib graph to the Chart constructor.
3. Add a Matplotlib chart to an PDF document
Now it's time to create our PDF document and add content to it.
# New import (s) from borb.pdf.document import Documentfrom borb.pdf.page.page import Pagefrom borb.pdf.pdf import PDFfrom borb.pdf.canvas.layout.page_layout.multi_column_layout import MultiColumnLayoutfrom borb.pdf.canvas.layout.page_layout.page_layout import PageLayoutfrom borb.pdf.canvas.layout.text.paragraph import Paragraph # Create empty Documentpdf = Document () # Create empty Pagepage = Page () # Add Page to Documentpdf.append_page (page) # Create PageLayoutlayout: PageLayout = MultiColumnLayout (page) # Write titlelayout.add (Paragraph ("About Lorem Ipsum") Font_size=Decimal (20), font= "Helvetica-Bold"))
We will use hyphens in this PDF to ensure a smoother layout of the text. The hyphen in borb is very simple:
# New import (s) from borb.pdf.canvas.layout.hyphenation.hyphenation import Hyphenation # Create hyphenation algorithmhyphenation_algorithm: Hyphenation = Hyphenation ("en-gb") # Write paragraphlayout.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)
Now we can add a pie chart using the function we declared earlier
# Write graphlayout.add (create_piechart (["Loren", "Ipsum", "Dolor"], [0.6,0.3,0.1]))
Next we will write three more Paragraph objects. One of them will represent more than just references (side borders, different fonts, etc.).
# Write paragraphlayout.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 paragraphlayout.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 paragraphlayout.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)
Let's add another drawing.
# Write graphlayout.add (create_piechart (["Loren", "Ipsum", "Dolor", "Sit", "Amet"], [600,30,89,100,203])
There is also a paragraph (Paragraph):
# Write paragraphlayout.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)
Finally, we can store the document (Document):
# Write to diskwith open ("output.pdf", "wb") as pdf_file_handle: PDF.dumps (pdf_file_handle, pdf)
Running this code produces an PDF document like this:
These are all the contents of the article "how Python integrates matplotlib diagrams into PDF". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.