Creating and Customizing Pie Charts in Python with Matplotlib
Topic Overview and Actualization
Hello and welcome! In today's lesson, we dive into the world of Pie Charts in Python. Pie charts enable you to depict proportions visually, illustrating populations by continents where each slice represents a part of the total, for instance. Today, you'll learn to create and customize pie charts in Python using Matplotlib.
Introduction to Pie Charts
Pie charts are a type of graphic where the circle (the "pie") is divided into "slices," each of which represents a different category. Imagine a pizza where each slice is a fruit type - apples, oranges, bananas, and grapes. The size of each slice corresponds to the quantity of each fruit. To create interactive pie charts, we'll be using the well-established Python data visualization library: Matplotlib.
Your First Pie Chart: Dataset
Let's create a pie chart depicting the favorite fruits of a group of people, which could represent consumer preferences in a market survey. We will use this dataset:
Your First Pie Chart: Sharing the Pie
Let's start crafting a pie chart for this dataset.
Pie Chart Components:
- Slices: Portions of each fruit preference.
- Labels: Names of the fruits.
Crafting a Pie Chart:
With the Matplotlib library, we can create an informative and appealing pie chart. It takes the data array and labels for it. We will also pass the startangle parameter, which rotates the graph, to make its layout fancier.
Result:

This chart helps us visualize the division of preferences, much like how market shares are illustrated in business.
Using 'explode' to Highlight a Slice
To highlight a specific slice in a pie chart, we slightly separate it from the rest of the pie, a process referred to as "exploding" the slice.
Consider an array or a tuple you pass to explode. Typically, most of the values are zero, except for the slice we want to highlight. For example:
Here, we are exploding the first slice, i.e., moving it out slightly. Let's see what that looks like in a full code bloc:
Result:

Now our pie chart highlights the apples, or the first slice in our pie.


