from reportlab.graphics.charts.piecharts import Pie
Here we have two set of data used to generate Pie Chart.
pc.data = [10,20,30,40,50,60]
pc.labels = ['a','b','c','d','e','f']
Using this data the graph is here. from reportlab.lib import colors
my_path='G:\\My drive\\testing\\pypdf2\\my_pdf.pdf'
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.piecharts import Pie
from student_data import my_classes,my_Nos
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)
from reportlab.graphics import renderPDF
renderPDF.drawToFile(d, my_path, '')
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 student in class as list
# print(my_classes,my_Nos) # for checking output
We will connect to above code and get the variables my_classes and my_Nos.
from student_data import my_classes,my_Nos
Using data sources for drawing Pie chart
pc.data=my_Nos
pc.labels=my_classes
Full code of our Main file using database data as source is here.
from reportlab.lib import colors
my_path='G:\\My drive\\testing\\pypdf2\\my_pdf.pdf'
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.piecharts import Pie
from student_data import my_classes,my_Nos
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)
from reportlab.graphics import renderPDF
renderPDF.drawToFile(d, my_path, '')
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.