Page 167 - Touhpad Ai
P. 167
The function pie() is used to plot a pie chart.
Program 5: Create a Pie chart for different category of books read in a month using Python.
Story Books Fiction Murder Mystery Comic Books Self-help Books
Books Read in a Month 30 20 25 10
Code:
import matplotlib.pyplot as plt
# Data
labels = ['Fiction', 'Murder Mystery', 'Comic Books', 'Self-help Books']
sizes = [30, 20, 25, 10]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0) # explode the first slice (Fiction)
# Create pie chart using pie() function.
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.0f%%', shadow=True, startangle=140)
# Add title
plt.title('No. of Books Read in a Month')
# Equal aspect ratio ensures that pie is drawn as a circle.
plt.axis('equal')
# Show plot
plt.show()
Output:
This code will generate a pie chart with slices representing the number of books read in a month for each category:
Fiction, Murder Mystery, Comic Books, and Self-help books. The first slice (Fiction) is exploded to highlight it explode
parameter. The ‘autopct’ parameter displays the percentage value of each slice (each label will show the percentage
value of the corresponding slice, rounded to zero decimal place), and ‘shadow’ adds a shadow effect. The ‘startangle’
parameter rotates the start of the pie chart to 140 degrees for better visual appeal.
Data Visualization 165

