Matplotlib provides support for pie charts using the pie() function. This module allows the creation of various types of graphs, including pie charts, which visually represent data proportions in a circular format.
Creating a simple Pie Chart
Below is an example of how to create a basic pie chart using Matplotlib:
Example: Simple Pie Chart
import matplotlib.pyplot as plt
# Data to plot
labels = ['Angola', 'Brazil', 'Portugal', 'Cape Verde']
sizes = [1215, 2130, 2245, 2210]
# Define colors for each segment
colors = ['lightcoral', 'gold', 'yellowgreen', 'lightskyblue']
# Explode the first slice
explode = (0.1, 0, 0, 0)
# Create pie chart
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)
# Ensure the pie chart is a circle
plt.axis('equal')
# Display the chart
plt.show()

Explanation of the Code:
- The
labelslist defines the names of the categories. - The
sizeslist specifies the values corresponding to each category. - The
colorslist determines the color of each segment. - The
explodeparameter offsets a selected slice from the center. - The
autopct='%1.1f%%'argument adds percentage labels to each segment. - The
shadow=Trueargument adds a shadow effect. - The
startangle=140rotates the chart for better visibility. - The
plt.axis('equal')ensures the pie chart remains circular.
Adding a Legend to the Pie Chart
You can add a legend to indicate what each segment represents using the legend() function.
Example: Pie Chart with Legend
import matplotlib.pyplot as plt
# Data to plot
labels = ['Angola', 'Brazil', 'Portugal', 'Cape Verde']
sizes = [1215, 2130, 2245, 2210]
# Define colors for each segment
colors = ['lightcoral', 'gold', 'yellowgreen', 'lightskyblue']
# Explode the first slice
explode = (0.1, 0, 0, 0)
# Create pie chart
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)
# Add legend
plt.legend(labels, loc="upper right")
# Ensure the pie chart is a circle
plt.axis('equal')
# Display the chart
plt.show()

Legend positioning options
The loc parameter defines the position of the legend. Possible values include:
best(automatically selects the best position)upper rightupper leftlower leftlower rightcenter leftcenter rightlower centerupper centercenter
Conclusion
Pie charts are an effective way to visualize proportions in a dataset. Using Matplotlib, you can customize the chart by adjusting slice sizes, labels, colors, explosion effects, and legend positions.
Copyright statement: Unless otherwise indicated, all articles are original to this site, please cite the source when sharing.
Article link:http://pybeginners.com/python-data-manipulation/python-matplotlib-how-to-create-a-pie-chart-in-matplotlib/
License agreement:Creative Commons Attribution-NonCommercial 4.0 International License