Pie charts are perfect for showing proportions and percentage distribution of data in a simple and visually appealing way.
In this guide, you’ll learn how to create and customize pie charts using Matplotlib.
πΉ What is a Pie Chart?
A pie chart is a circular graph divided into slices, where each slice represents a proportion of the whole.
π It answers:
- What percentage does each category contribute?
- How is data distributed in parts?
πΉ When to Use Pie Chart?
Use a pie chart when:
β You want to show percentage distribution
β You have limited categories (ideally < 5)
β You want a simple visual representation
πΉ Basic Example
import matplotlib.pyplot as pltlabels = ['Python', 'Java', 'C++']
sizes = [45, 30, 25]plt.pie(sizes, labels=labels)
plt.title("Pie Chart Example")plt.show()
πΉ Output Explanation
labelsβ Categoriessizesβ Values (proportions)plt.pie()β Creates the pie chart
πΉ Real-Life Use Cases
π Market share analysis
π» Programming language usage
π° Budget distribution
π¦ Product category contribution
πΉ Adding Percentages
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title("Pie Chart with Percentages")plt.show()
π Displays percentage values on each slice.
πΉ Customizing Pie Chart
colors = ['gold', 'lightblue', 'lightgreen']plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
plt.title("Customized Pie Chart")plt.show()
πΉ Customization Options
| Feature | Example | Description |
|---|---|---|
| Colors | colors=['red','blue'] | Set slice colors |
| autopct | '%1.1f%%' | Show percentages |
| startangle | startangle=90 | Rotate chart |
| explode | [0.1, 0, 0] | Highlight a slice |
πΉ Exploding a Slice
explode = [0.1, 0, 0]plt.pie(sizes, labels=labels, explode=explode, autopct='%1.1f%%')
plt.title("Exploded Pie Chart")plt.show()
π Highlights important category.
πΉ Donut Chart (Advanced)
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
centre_circle = plt.Circle((0,0), 0.70, fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)plt.title("Donut Chart")plt.show()
πΉ Saving the Chart
plt.savefig("pie_chart.png")
πΉ Best Practices
β Use only a few categories
β Ensure total = 100%
β Avoid too many colors
β Use labels clearly
β Prefer bar chart if data is complex
π Useful Resources
- π Matplotlib Docs: https://matplotlib.org/stable/contents.html
- π Tutorials: https://matplotlib.org/stable/tutorials/index.html
- π Python Official: https://www.python.org/
π Conclusion
Pie charts are simple yet powerful for showing proportions. When used correctly, they make your data easy to understand at a glance.
However, use them wiselyβtoo many slices can make them hard to read.
π Hashtags
#Matplotlib #Python #DataVisualization #PieChart #DataScience #MachineLearning #Coding #Analytics #Programming #AI #BigData