To create a pie chart using matplotlib:
import matplotlib.pyplot as plt my_data = [value1, value2, value3, ...] my_labels = 'label1', 'label2', 'label3', ... plt.pie(my_data, labels=my_labels, autopct='%1.1f%%') plt.title('My Title') plt.axis('equal') plt.show()
Steps to Create a Pie Chart using Matplotlib
Step 1: Gather the Data for the Pie Chart
To start, gather your data for the pie chart.
For example, let’s use the following data about the status of tasks:
Tasks Pending | 300 |
Tasks Ongoing | 500 |
Tasks Completed | 700 |
The goal is to create a pie chart based on the above data.
Step 2: Plot the Pie Chart using Matplotlib
Next, plot the pie chart using matplotlib.
You can use the template below to plot the chart:
import matplotlib.pyplot as plt my_data = [value1, value2, value3, ...] my_labels = 'label1', 'label2', 'label3', ... plt.pie(my_data, labels=my_labels, autopct='%1.1f%%') plt.title('My Title') plt.axis('equal') plt.show()
For our example:
import matplotlib.pyplot as plt my_data = [300, 500, 700] my_labels = 'Tasks Pending', 'Tasks Ongoing', 'Tasks Completed' plt.pie(my_data, labels=my_labels, autopct='%1.1f%%') plt.title('My Tasks') plt.axis('equal') plt.show()
Run the code in Python and you’ll get the pie chart.
Step 3: Style the Chart
You can further style the pie chart by adding:
- Start angle
- Shadow
- Colors
- Explode component
Here is the code for the styled chart:
import matplotlib.pyplot as plt my_data = [300, 500, 700] my_labels = 'Tasks Pending', 'Tasks Ongoing', 'Tasks Completed' my_colors = ['lightblue', 'lightsteelblue', 'silver'] my_explode = (0, 0.1, 0) plt.pie(my_data, labels=my_labels, autopct='%1.1f%%', startangle=15, shadow=True, colors=my_colors, explode=my_explode) plt.title('My Tasks') plt.axis('equal') plt.show()
Run the code, and you’ll get the styled chart.
You may check the following guide that explains the steps to create scatter, line and bar charts using matplotlib.