Introduction
Pie charts, a broadly used visualization instrument, signify information proportions in a round format. Every slice corresponds to a class, facilitating fast comparisons. Right here, we glance into creating pie charts utilizing Matplotlib.

Significance of Pie Charts in Knowledge Visualization
Pie charts play a vital position in information visualization for a number of causes. Firstly, they supply a visible illustration of proportions or percentages, permitting viewers to rapidly perceive the distribution of knowledge. This makes it simpler to determine patterns, traits, or disparities within the information.
Moreover, pie charts are helpful for highlighting the relative significance of various classes. By evaluating the sizes of the slices, viewers can simply decide which classes are bigger or smaller in relation to one another. This may be significantly useful when presenting information in a concise and visually interesting method.
Moreover, pie charts are efficient in conveying info to a variety of audiences. They’re intuitive and straightforward to know, even for people who might not have a robust background in information evaluation. This makes pie charts a beneficial instrument for speaking complicated info in a transparent and accessible manner.
Additionally Learn: 12 Knowledge Plot Sorts for Visualization from Idea to Code
Getting Began with Matplotlib
Putting in Matplotlib
Earlier than you can begin utilizing Matplotlib, you should set up it in your system. Putting in Matplotlib is an easy course of. You need to use the pip package deal supervisor to put in it by operating the next command in your terminal:
Code:
!pip set up matplotlib
Ensure you have Python and pip put in in your system earlier than operating this command. As soon as the set up is full, you possibly can confirm it by importing Matplotlib in your Python script with none errors.
Importing Matplotlib
To make use of Matplotlib in your Python script, you should import it first. You’ll be able to import the pyplot module from Matplotlib, which offers a easy interface for creating and customizing plots. Right here’s an instance of learn how to import Matplotlib:
Code:
import matplotlib.pyplot as plt
By conference, Matplotlib is normally imported as `plt` for brevity. This lets you use shorter operate names when creating plots.
Additionally Learn: Matplotlib | Matplotlib For Knowledge Visualization, Exploration
Making a Primary Pie Chart
Understanding the Knowledge
Earlier than we dive into making a pie chart utilizing Matplotlib, let’s first perceive the info that we’ll be working with. A pie chart is a round statistical graphic that’s divided into slices to signify completely different classes or proportions of an entire. Every slice of the pie chart represents a selected class, and the dimensions of the slice corresponds to the proportion of that class in the entire.
In our instance, we’ll create a pie chart to visualise the distribution of gross sales for various merchandise in a retailer. We are going to use a easy dataframe with two columns: “Product” and “Gross sales”. The “Product” column will include the names of the merchandise, and the “Gross sales” column will include the corresponding gross sales figures.
Plotting a Easy Pie Chart
To plot a easy pie chart utilizing Matplotlib, we have to import the mandatory libraries and create a dataframe with the info we need to visualize. We will then use the `plt.pie()` operate to create the pie chart.
Right here’s an instance code snippet that demonstrates learn how to create a primary pie chart:
Code:
import matplotlib.pyplot as plt
# Create a dataframe with the info
information = {'Product': ['Product A', 'Product B', 'Product C', 'Product D'],
'Gross sales': [350, 450, 300, 600]}
df = pd.DataFrame(information)
# Plot the pie chart
plt.pie(df['Sales'], labels=df['Product'])
plt.present()
Output:

Customizing Pie Chart Colours
To customise the colours of the slices within the pie chart, we are able to move a listing of colours to the `colours` parameter of the `plt.pie()` operate. Every coloration within the listing corresponds to a slice within the pie chart.
Right here’s an instance code snippet that demonstrates learn how to customise the colours of a pie chart:
Code:
import matplotlib.pyplot as plt
# Create a dataframe with the info
information = {'Product': ['Product A', 'Product B', 'Product C', 'Product D'],
'Gross sales': [350, 450, 300, 600]}
df = pd.DataFrame(information)
# Outline customized colours
colours = ['Pink', 'cyan', 'skyblue', 'yellow']
# Plot the pie chart with customized colours
plt.pie(df['Sales'], labels=df['Product'], colours=colours)
plt.present()
Output:

Including Labels and Percentages
So as to add labels and percentages to the slices within the pie chart, we are able to use the `autopct` parameter of the `plt.pie()` operate. The `autopct` parameter accepts a format string that specifies how the chances ought to be displayed.
Right here’s an instance code snippet that demonstrates learn how to add labels and percentages to a pie chart:
Code:
import matplotlib.pyplot as plt
# Create a dataframe with the info
information = {'Product': ['Product A', 'Product B', 'Product C', 'Product D'],
'Gross sales': [350, 450, 300, 600]}
df = pd.DataFrame(information)
# Plot the pie chart with labels and percentages
plt.pie(df['Sales'], labels=df['Product'], autopct="%1.1f%%")
plt.present()
Output:

Exploding Slices
To emphasise a selected slice within the pie chart, we are able to “explode” it by utilizing the `explode` parameter of the `plt.pie()` operate. The `explode` parameter accepts a listing of values that specifies the extent to which every slice ought to be exploded.
Right here’s an instance code snippet that demonstrates learn how to explode a slice in a pie chart:
Code:
import matplotlib.pyplot as plt
# Create a dataframe with the info
information = {'Product': ['Product A', 'Product B', 'Product C', 'Product D'],
'Gross sales': [350, 450, 300, 600]}
df = pd.DataFrame(information)
# Explode the second slice
explode = [0, 0.1, 0, 0]
# Plot the pie chart with an exploded slice
plt.pie(df['Sales'], labels=df['Product'], explode=explode)
plt.present()
Output:

Including a Legend
So as to add a legend to the pie chart, we are able to use the `plt.legend()` operate. The legend offers a visible illustration of the labels within the pie chart.
Right here’s an instance code snippet that demonstrates learn how to add a legend to a pie chart:
Code:
import matplotlib.pyplot as plt
# Create a dataframe with the info
information = {'Product': ['Product A', 'Product B', 'Product C', 'Product D'],
'Gross sales': [350, 450, 300, 600]}
df = pd.DataFrame(information)
# Plot the pie chart with a legend
plt.pie(df['Sales'], labels=df['Product'])
plt.legend()
plt.present()
Output:

Saving and Displaying the Chart
To avoid wasting the pie chart as a picture file, we are able to use the `plt.savefig()` operate. The `plt.savefig()` operate accepts a file title and the specified file format as parameters.
Right here’s an instance code snippet that demonstrates learn how to save a pie chart as a picture file:
Code:
import matplotlib.pyplot as plt
# Create a dataframe with the info
information = {'Product': ['Product A', 'Product B', 'Product C', 'Product D'],
'Gross sales': [350, 450, 300, 600]}
df = pd.DataFrame(information)
# Plot the pie chart
plt.pie(df['Sales'], labels=df['Product'])
# Save the pie chart as a picture file
plt.savefig('pie_chart.png')
plt.present()
Output:

Troubleshooting and Suggestions
Dealing with Lacking or Invalid Knowledge
When making a pie chart utilizing Matplotlib, it is very important deal with lacking or invalid information appropriately. In case your dataset incorporates lacking values or invalid entries, it could actually have an effect on the accuracy and reliability of your pie chart.
To deal with lacking or invalid information, you should utilize the pandas library in Python to create a DataFrame and clear the info earlier than plotting the pie chart. You’ll be able to take away any rows or columns with lacking values utilizing the dropna() operate. Moreover, you possibly can exchange invalid entries with applicable values utilizing the fillna() operate.
Right here’s an instance of how one can deal with lacking or invalid information:
Code:
import pandas as pd
import matplotlib.pyplot as plt
# Create a DataFrame with lacking or invalid information
information = {'Class': ['A', 'B', 'C', 'D'],
'Worth': [10, None, 20, 'Invalid']}
df = pd.DataFrame(information)
# Substitute invalid entries with applicable values
df['Value'] = pd.to_numeric(df['Value'], errors="coerce")
# Drop rows with lacking or invalid numeric values
df = df.dropna()
# Plot the pie chart
plt.pie(df['Value'], labels=df['Category'])
plt.present()
Output:
By dealing with lacking or invalid information earlier than creating the pie chart, you possibly can be sure that your chart precisely represents the out there information.
Coping with Overlapping Labels
Generally, when making a pie chart with numerous classes, the labels can overlap and grow to be unreadable. This could make it tough for viewers to interpret the chart successfully.
To cope with overlapping labels, you possibly can regulate the dimensions and place of the labels utilizing the labeldistance and autopct parameters within the plt.pie() operate. The labeldistance parameter controls the gap of the labels from the middle of the pie chart, whereas the autopct parameter specifies the format of the share values displayed on the chart.
Right here’s an instance of how one can cope with overlapping labels:
Code:
import matplotlib.pyplot as plt
# Create a pie chart with overlapping labels
labels = ['Category 1', 'Category 2', 'Category 3', 'Category 4', 'Category 5']
sizes = [20, 30, 10, 15, 25]
# Modify the dimensions and place of the labels
plt.pie(sizes, labels=labels, labeldistance=1.1, autopct="%1.1f%%")
plt.present()
Output:

By adjusting the labeldistance and autopct parameters, you possibly can be sure that the labels in your pie chart are clear and readable.
Avoiding Deceptive Pie Charts
Pie charts can typically be deceptive if not used appropriately. It is very important keep away from utilizing pie charts when the info doesn’t signify components of an entire or when there are too many classes, as it could actually make the chart tough to interpret.
To keep away from deceptive pie charts, think about using different varieties of charts, comparable to bar charts or line charts, relying on the character of your information. These charts can present a clearer illustration of the info and make it simpler for viewers to know the data being offered.
Moreover, be sure that the sizes of the pie slices precisely signify the proportions of the info. You’ll be able to obtain this by sorting the info in descending order earlier than creating the pie chart.
Enhancing Accessibility and Usability
When creating pie charts, it is very important improve accessibility and value for all viewers. Take into account the next ideas:
- Use excessive distinction colours to make sure that the chart is readable for people with visible impairments.
- Present a legend or labels to obviously determine every class within the chart.
- Keep away from utilizing 3D results or shadows, as they will make the chart tough to interpret.
- Use applicable font sizes for the labels to make sure readability.
- Take a look at the chart on completely different units and display screen sizes to make sure that it’s responsive and accessible.
By following the following tips, you possibly can improve the accessibility and value of your pie charts and be sure that they successfully talk the meant info.
Conclusion
In conclusion, creating and customizing pie charts utilizing Matplotlib generally is a highly effective instrument for visualizing information. By following the rules and ideas offered on this information, you possibly can create informative and visually interesting pie charts that successfully talk your information.
Keep in mind to deal with lacking or invalid information appropriately, cope with overlapping labels, keep away from deceptive pie charts, and improve accessibility and value. With these issues in thoughts, you possibly can create pie charts that successfully convey your information insights to your viewers.
So go forward, discover the assorted customization choices out there in Matplotlib, and begin creating your individual visually beautiful pie charts!


