Use Tkinter and matplotlib to draw a pie chart.
When learning python, we will always use some common modules. Next I will explain in detail how to use two different methods to draw a pie chart.
First, use the canvas in [Tkinter] to draw a pie chart:
From tkinter import Tk, Canvas
Def DrawPie ():
# Create window
Windows = Tk ()
# Add a title
Windows. title ("Pie Chart ")
# Setting canvas styles
Canvas = Canvas (windows, height = 500, width = 500)
# Package the canvas into a window
Canvas. pack ()
# Use create_arc of the canvas to draw a pie, (400,400) and (100,100) as the rectangle around the pie,
# Start = start of angle, extent = degree of rotation, fill = fill color
Canvas. create_arc (400,400,100,100, start = 0, extent = 36, fill = "red ")
Canvas. create_arc (400,400,100,100, start = 36, extent = 72, fill = "green ")
Canvas. create_arc (400,400,100,100, start = 108, extent = 108, fill = "yellow ")
Canvas. create_arc (400,400,100,100, start = 216, extent = 144, fill = "blue ")
# Add content for each slice, with the center of the circle (250,250)
Canvas. create_text (430,200, text = "36 °", font = (" 文 ", 20 ))
Canvas. create_text (330,100, text = "72 °", font = (" 文 ", 20 ))
Canvas. create_text (90,200, text = "108 °", font = (" 文 ", 20 ))
Canvas. create_text (390,370, text = "144 °", font = (" 文 ", 20 ))
# Enable message loop
Windows. mainloop ()
If _ name _ = '_ main __':
# Call Method
DrawPie ()
The above method is to use the Tkinter canvas to draw a pie chart. Next let's look at the pyplot in the third-party module matplotlib:
From matplotlib import pyplot
# Chinese support
Pyplot. rcParams ['font. sans-serif'] = ['simhei']
# Used to display Chinese labels normally
Pyplot. rcParams ['axes. unicode_minus '] = False # It is used to display a negative number normally.
Def showPieChart ():
# Call the pie method in the pyplot module to draw a pie chart. The first parameter of the pie method is the proportion of each part. Other parameters are some modified labels for the pie chart,
Labels is the description,Startangle indicates the starting angle of the painting, and counterclock indicates the direction of the painting (the default value is counter-clockwise)
Pyplot. pie ([108,144, 108], labels = ["36 °", "72 °", "144 °", "°"], startangle = 90, counterclock = False)
# Display graphics
Pyplot. show ()
If _ name _ = '_ main __':
# Call a function
ShowPieChart ()
In fact, the two methods are similar, but the application modules are different. The first method can only draw a graph, but cannot add the content of the pie chart. The second method encapsulates the pie chart style, various styles can be added.