Pie Chart in PDF File

Interactive Google Colab Practice Notebook

Practice generating pie charts with slice popouts, customized font styling, and querying data from SQLite/MySQL databases using ReportLab directly inside Google Colab.

View on GitHub Open In Colab
Pie chart in Python PDF using ReportLab with data from SQLite or MySQL database with options

Pie Chart with Options 🔝

from reportlab.graphics.charts.piecharts import Pie

Here we have two sets of data used to generate the Pie Chart:

pc.data = [10, 20, 30, 40, 50, 60]
pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']

Using this data, the graph is rendered below:

Pie graph in PDF file

In this format, we can collect sample data from SQLite or MySQL databases and display the graph dynamically.

Full code is shown below. Different options are explained using comments:

from pathlib import Path
from reportlab.lib import colors
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.piecharts import Pie
from student_data import my_classes, my_Nos
from reportlab.graphics import renderPDF

output_dir = Path('output')
output_dir.mkdir(exist_ok=True)
my_path = output_dir / 'pie_chart_options.pdf'

d = Drawing(800, 800) # width, height
pc = Pie()

pc.x = 120
pc.y = 300
pc.width = 400
pc.height = 400
# pc.data = [10, 20, 30, 40, 50, 60]
# pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
pc.data = my_Nos
pc.labels = my_classes
pc.sideLabels = 0
pc.simpleLabels = 0
pc.slices.strokeWidth = 0.5
pc.slices[3].popout = 10
pc.slices[3].strokeWidth = 2
pc.slices[3].strokeDashArray = [2, 2]
pc.slices[3].labelRadius = 1.3
pc.slices[3].fontColor = colors.red
pc.slices[3].fontSize = 26
d.add(pc)

renderPDF.drawToFile(d, str(my_path), '')
print(f"PDF created: {my_path}")

Pie Chart Using Data from Database Table 🔝

Pie graph from different Data sources PDF file

We will use an SQLite database student table. Scripts can easily be changed to get data from MySQL database tables.

Download sample SQLite database with student table

We can also use MySQL database.

Full student table with SQL Dump for MySQL database

student_data.py
from sqlalchemy import create_engine
my_conn = create_engine("sqlite:///G:\My Drive\testing\my_db\my_db.db")
# my_conn = create_engine("mysql+mysqldb://userid:pw@localhost/my_tutorial")
q = "SELECT class, count(*) as no FROM student GROUP BY class"
my_cursor = my_conn.execute(q)   # getting record set
my_result = my_cursor.fetchall() # create a list
my_classes = [row[0] for row in my_result] # class as list
my_Nos = [row[1] for row in my_result]   # number of students in class as list
# print(my_classes, my_Nos) # for checking output

We will connect to the above code and get the variables my_classes and my_Nos:

from student_data import my_classes, my_Nos

Using data sources for drawing the Pie Chart:

pc.data = my_Nos
pc.labels = my_classes

Full code of our main file using database data as the source is shown below:

from pathlib import Path
from reportlab.lib import colors
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.piecharts import Pie
from student_data import my_classes, my_Nos
from reportlab.graphics import renderPDF

output_dir = Path('output')
output_dir.mkdir(exist_ok=True)
my_path = output_dir / 'pie_chart_database.pdf'

d = Drawing(800, 800) # width, height
pc = Pie()
pc.x = 120
pc.y = 300
pc.width = 400
pc.height = 400
# pc.data = [10, 20, 30, 40, 50, 60]
pc.data = my_Nos
# pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
pc.labels = my_classes
pc.sideLabels = 0
pc.simpleLabels = 0
pc.slices.strokeWidth = 0.5
pc.slices[3].popout = 3
pc.slices[3].strokeWidth = 2
pc.slices[3].strokeDashArray = [2, 2]
pc.slices[3].labelRadius = 1.1
pc.slices[3].fontColor = colors.red
pc.slices[3].fontSize = 26

d.add(pc)
renderPDF.drawToFile(d, str(my_path), '')
print(f"PDF created: {my_path}")
Pie graph from student table data in PDF file

Practical Uses of Pie Charts in ReportLab

Pie charts effectively illustrate proportions and percentage distributions within professional PDF documents:

  • Budget & Resource Allocation: Display expenditure breakdowns or department resource distributions as clear relative shares.
  • Demographic & Enrollment Summaries: Show student enrollment counts grouped by academic classes queried directly from SQLite or MySQL tables.
  • Survey & Polling Results: Present segmented survey responses or categorical feedback percentages visually.

Common Errors & Troubleshooting

  • Data and Labels Length Mismatch: Ensure the length of pc.data exactly matches the length of pc.labels; otherwise, ReportLab will raise an index or indexing configuration error.
  • Slice Popout Index Out of Range: When accessing individual slices via index (e.g., pc.slices[3]), confirm that the dataset contains at least 4 items (indexing starts at 0).
  • Database Connection String Issues: When using SQLAlchemy, ensure your connection URI (SQLite or MySQL) correctly references the absolute or relative file path and credentials.

Frequently Asked Questions (FAQ)

Q: How do I highlight a specific category slice in a ReportLab pie chart?
A: You can pop out a slice by setting its popout property, e.g., pc.slices[index].popout = 10.

Q: Can I render labels outside the pie chart slices?
A: Yes, setting pc.sideLabels = 1 moves labels to the side, and you can adjust individual label distances using labelRadius.

Further Reading & Related Tutorials


Python PDF Shapes in PDF Bar charts in PDF Line Charts
PDF Mark sheet by using data from SQLite database



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer