To create a pie chart in Python 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 in Python using Matplotlib
Step 1: Install the Matplotlib package
Install the Matplotlib package if you haven’t already done so:
pip install matplotlib
Step 2: Gather the Data for the Pie Chart
Next, gather the 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 3: 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 script in Python and you’ll get the pie chart.
Step 4: Style the Chart
You can further style the pie chart by adding:
- Start angle
- Shadow
- Colors
- Explode component
Here is the script 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 script, 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.