Matplotlib Pie Charts (Python Programming)
Learn Matplotlib Pie Charts (Python Programming) step by step with clear examples and exercises.
Title: Matplotlib Pie Charts (Python Programming)
Why This Matters
Matplotlib is a crucial library for data visualization in Python, offering various ways to represent data graphically. Pie charts are popular tools for comparing proportions and presenting categorical data. By learning how to create and customize pie charts using Matplotlib, you can effectively communicate your findings or make data more engaging in presentations.
Prerequisites
To follow along with this lesson, you should have a basic understanding of Python programming concepts and the NumPy library. Familiarity with Matplotlib is not required but will be helpful if you've worked with other types of plots before.
Understanding Data Structures
Before diving into pie charts, it's essential to understand data structures like lists, tuples, and dictionaries in Python. These data structures are commonly used when working with Matplotlib.
Core Concept
Importing Necessary Libraries
To create pie charts using Matplotlib, we first need to import the necessary libraries:
import matplotlib.pyplot as plt
import numpy as np
Creating a Simple Pie Chart
Next, let's create a simple pie chart with two slices representing different categories:
labels = ['Category 1', 'Category 2']
sizes = [30, 70]
colors = ['#9C515D', '#3776AB']
plt.pie(sizes, labels=labels, colors=colors)
plt.show()
In this example, labels contains the names of our categories, sizes represents their proportions (in percentages), and colors specifies the color for each slice. The plt.pie() function generates the pie chart, while plt.show() displays it on the screen.
Customizing Pie Charts
Matplotlib offers many options to customize your pie charts:
- Autopct: Controls the formatting of the percentage labels on each slice. For example, you can use
autopct='%1.1f%%'to display percentages with one decimal place. - Explode: Allows you to separate slices by a certain angle, making them easier to compare. Set
explode=(0.1, 0)to create some space between the first and second slice in our example. - Startangle: Sets the starting angle of the pie chart. By default, it's at 90 degrees, but you can change it to better fit your data.
- Autopct_percentages: Controls whether percentage labels are displayed or not. Set
autopct='%1.1f%%'to show percentages with one decimal place.
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', explode=(0.1, 0), startangle=90)
plt.axis('equal') # Ensures the pie chart is circular
plt.show()
Creating a More Complex Pie Chart
To create a more complex pie chart, we can use data stored in a dictionary:
data = {'Category 1': [20, 35, 41], 'Category 2': [80, 65, 59]}
colors = ['#9C515D', '#3776AB']
fig, ax = plt.subplots(figsize=(6, 6))
for category, values in data.items():
ax.pie(values, label=category, colors=[colors[i] for i, _ in enumerate(data)][data.items().index(tuple([k, v]))], autopct='%1.1f%%')
ax.legend(loc='upper left', bbox_to_anchor=(1.05, 1), borderaxespad=0)
plt.show()
In this example, we have data for three time periods (20, 35, and 41 for Category 1, and 80, 65, and 59 for Category 2). We create a figure and axis for our plot using plt.subplots(), then iterate through each category to generate slices with the appropriate colors. Finally, we add a legend and customize its position using loc and bbox_to_anchor.
Worked Example
Let's create a more complex pie chart to demonstrate some of these customizations:
import matplotlib.pyplot as plt
import numpy as np
Data for our example
data = {'Category 1': [20, 35, 41], 'Category 2': [80, 65, 59]}
colors = ['#9C515D', '#3776AB']
Create a figure and axis for our plot
fig, ax = plt.subplots(figsize=(6, 6))
Iterate through each category and create a pie chart slice
for category, values in data.items():
ax.pie(values, label=category, colors=[colors[i] for i, _ in enumerate(data)][data.items().index(tuple([k, v]))], autopct='%1.1f%%', startangle=-90)
Add a legend and customize it
ax.legend(loc='upper left', bbox_to_anchor=(1.05, 1), borderaxespad=0)
Show the plot
plt.show()
In this example, we have data for three time periods (20, 35, and 41 for Category 1, and 80, 65, and 59 for Category 2). We create a figure and axis for our plot using `plt.subplots()`, then iterate through each category to generate slices with the appropriate colors. By setting `startangle=-90`, we rotate the pie chart so that the first slice starts at the bottom. Finally, we add a legend and customize its position using `loc` and `bbox_to_anchor`.
Common Mistakes
- Forgetting to call plt.show(): This will result in an empty plot or no output at all.
- Not normalizing data: If your data doesn't add up to 100%, Matplotlib will automatically normalize it, but this might not always produce the desired results. To avoid surprises, make sure that your data adds up to 100%.
- Ignoring autopct: By default, Matplotlib does not display percentage labels on pie charts. Make sure to set
autopctappropriately to show these values. - Not setting axis aspect ratio: If your pie chart is distorted or squashed, you might need to use
plt.axis('equal')to ensure that the plot is circular. - Misusing explode: Using too large a value for
explodecan make it difficult to compare slices. Be mindful of the space between your slices when using this option. - Not handling missing data: If you have missing values in your data, Matplotlib will throw an error. You can use NumPy's
nanmean()function to calculate the mean of a list excluding NaN values.
Common Mistake Examples
- Missing autopct:
plt.pie(sizes, labels=labels, colors=colors)
plt.show() # No percentage labels!
- Not handling missing data:
data = {'Category 1': [20, 35, 41], 'Category 2': [80, 65, nan]}
colors = ['#9C515D', '#3776AB']
fig, ax = plt.subplots(figsize=(6, 6))
for category, values in data.items():
ax.pie(values, label=category, colors=[colors[i] for i, _ in enumerate(data)][data.items().index(tuple([k, v]))])
ax.legend(loc='upper left', bbox_to_anchor=(1.05, 1), borderaxespad=0)
plt.show() # Error: invalid value encountered in double_scalars
- Correcting missing data:
import numpy as np
data = {'Category 1': [20, 35, 41], 'Category 2': [80, 65, np.nan]}
means = np.nanmean([[v for v in values if not np.isnan(v)] for values in data.values()])
for category, values in data.items():
data[category] = [v / means * 100 for v in values]
colors = ['#9C515D', '#3776AB']
fig, ax = plt.subplots(figsize=(6, 6))
for category, values in data.items():
ax.pie(values, label=category, colors=[colors[i] for i, _ in enumerate(data)][data.items().index(tuple([k, v]))], autopct='%1.1f%%')
ax.legend(loc='upper left', bbox_to_anchor=(1.05, 1), borderaxespad=0)
plt.show()
Practice Questions
- Create a pie chart with three categories: 'A', 'B', and 'C'. The proportions are 30%, 45%, and 25%. Customize the plot to display percentage labels and use different colors for each slice.
labels = ['A', 'B', 'C']
sizes = [30, 45, 25]
colors = ['#9C515D', '#3776AB', '#F781BF']
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
plt.show()
- Given the following data, create a pie chart and add a legend:
data = {'Category 1': [30, 40, 30], 'Category 2': [50, 40, 10]}
colors = ['#9C515D', '#3776AB']
fig, ax = plt.subplots(figsize=(6, 6))
for category, values in data.items():
ax.pie(values, label=category, colors=[colors[i] for i, _ in enumerate(data)][data.items().index(tuple([k, v]))], autopct='%1.1f%%')
ax.legend(loc='upper left', bbox_to_anchor=(1.05, 1), borderaxespad=0)
plt.show()
FAQ
Q: How can I change the color of the pie chart background?
A: To change the background color of your pie chart, you can use plt.rcParams['axes.facecolor'] = 'your_color'. For example, to set a white background:
plt.rcParams['axes.facecolor'] = 'white'
Q: How do I save my pie chart as an image file?
A: To save your plot as an image file (e.g., PNG), you can use the savefig() function:
plt.savefig('my_pie_chart.png')