How to plot a pie chart in Python
Learn to plot pie charts in Python. Explore different methods, tips, real-world applications, and how to debug common errors.
.png)
Pie charts are a powerful way to visualize proportional data in Python. They help you represent parts of a whole, which makes complex datasets easy to understand at a glance.
In this article, you'll explore several techniques to create effective pie charts. You will find practical tips for customization, see real-world applications, and get advice to debug common visualization issues.
Basic pie chart with matplotlib
import matplotlib.pyplot as plt
sizes = [35, 25, 20, 20]
plt.pie(sizes)
plt.show()--OUTPUT--[Output: A basic pie chart with 4 slices in default colors]
Creating a basic pie chart starts with your data, represented here by the sizes list. The values don't need to add up to 100; the plt.pie() function automatically calculates each slice's proportion of the whole.
After defining the chart with plt.pie(), you call plt.show() to render and display the visualization. This separation allows you to add more customizations before the final output is generated.
Customizing your pie charts
Now that you have a basic chart, you can make it more informative and visually appealing with labels, custom colors, and the explode parameter.
Using labels and percentage annotations
import matplotlib.pyplot as plt
sizes = [35, 25, 20, 20]
labels = ['Apples', 'Bananas', 'Oranges', 'Grapes']
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.axis('equal')
plt.show()--OUTPUT--[Output: A pie chart with fruit labels and percentage values on each slice]
Adding labels and percentages makes your chart much more descriptive. You can pass a list of strings to the labels parameter to name each slice. To display numerical values, the autopct parameter formats and adds percentage annotations automatically.
- The format string
'%1.1f%%'instructs Matplotlib to display each slice's value as a percentage with one decimal place. - Using
plt.axis('equal')ensures the pie chart is drawn as a circle rather than an oval, giving an accurate visual representation.
Customizing colors and styling
import matplotlib.pyplot as plt
sizes = [35, 25, 20, 20]
labels = ['Apples', 'Bananas', 'Oranges', 'Grapes']
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
plt.pie(sizes, labels=labels, colors=colors, shadow=True, startangle=90)
plt.axis('equal')
plt.show()--OUTPUT--[Output: A pie chart with custom colors, a shadow effect, and rotated by 90 degrees]
You can easily define a custom color scheme by passing a list of color values to the colors parameter. This lets you align the chart with a specific brand palette or simply improve its visual appeal.
- The
shadow=Trueargument adds a subtle drop shadow beneath the pie, giving it a bit of depth. - Using
startangle=90rotates the chart so the first slice starts at the top, which can be a more intuitive layout.
Creating an exploded pie chart with the explode parameter
import matplotlib.pyplot as plt
sizes = [35, 25, 20, 20]
labels = ['Apples', 'Bananas', 'Oranges', 'Grapes']
explode = (0.1, 0, 0, 0) # only "explode" the first slice
plt.pie(sizes, labels=labels, explode=explode, autopct='%1.1f%%')
plt.show()--OUTPUT--[Output: A pie chart with the "Apples" slice pulled slightly away from the center]
To emphasize a particular slice, you can use the explode parameter. This effectively pulls a piece of the pie away from the center, which is a great way to draw attention to important data points.
- The
explodeparameter takes a tuple of values that must match the number of slices in your chart. - Each value in the tuple specifies how far to offset the corresponding slice. A non-zero value like
0.1moves the slice out by a fraction of the radius, while0keeps it in place.
Advanced pie chart techniques
Building on your matplotlib skills, you can now create donut charts or use libraries like pandas and plotly to handle more complex data visualizations.
Creating donut charts with nested pie() calls
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Outer ring
ax.pie([35, 25, 20, 20], labels=['Apples', 'Bananas', 'Oranges', 'Grapes'],
radius=1.0, wedgeprops=dict(width=0.3))
# Inner ring
ax.pie([60, 40], labels=['Fruits', 'Vegetables'], radius=0.7,
wedgeprops=dict(width=0.3))
plt.show()--OUTPUT--[Output: A donut chart with an outer ring showing fruit types and an inner ring showing broad categories]
You can create a donut chart by layering two pie charts on the same axes. This technique starts with plt.subplots() to get an axes object, ax, which allows you to draw multiple plots in the same space. You then make two separate calls to ax.pie()—one for the outer ring and another for the inner one.
- The
radiusparameter in each call controls the size of the rings, with the inner ring using a smaller value to fit inside the outer one. - The key to the donut effect is the
wedgepropsparameter. By passing it a dictionary likedict(width=0.3), you set the width of the wedges and create the hollow center.
Using pandas to create pie charts
import pandas as pd
import matplotlib.pyplot as plt
data = pd.Series([35, 25, 20, 20], index=['Apples', 'Bananas', 'Oranges', 'Grapes'])
data.plot.pie(autopct='%1.1f%%', figsize=(6, 6))
plt.title('Fruit Distribution')
plt.ylabel('') # Hide the y-label
plt.show()--OUTPUT--[Output: A pie chart created using pandas with title "Fruit Distribution"]
If your data is already in a pandas DataFrame or Series, you can create a pie chart directly. The pd.Series object holds both the values and their corresponding labels in its index, streamlining the setup.
- You can generate the plot by calling the
.plot.pie()method right on your Series. - Since pandas uses Matplotlib in the background, you can still use functions like
plt.title()for customization. - Setting
plt.ylabel('')is a handy way to hide the default y-axis label for a cleaner look.
Creating interactive pie charts with plotly
import plotly.express as px
labels = ['Apples', 'Bananas', 'Oranges', 'Grapes']
values = [35, 25, 20, 20]
fig = px.pie(names=labels, values=values, title='Fruit Distribution')
fig.show()--OUTPUT--[Output: An interactive pie chart that allows hovering, zooming, and other interactions]
For creating interactive visualizations, the plotly library is a powerful alternative to Matplotlib. Its high-level plotly.express module, imported as px, makes building charts straightforward. You can generate a pie chart by calling px.pie() and passing your data to the values and names parameters.
- Unlike static charts, Plotly figures are interactive by default—you can hover over slices to see details without any extra code.
- The final chart is rendered by calling
fig.show(), which opens the visualization with built-in controls for zooming and exporting.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the pie chart techniques you've explored, Replit Agent can turn them into production-ready tools. You could build applications like:
- A business intelligence dashboard that visualizes market share with interactive donut charts.
- A survey analysis tool that automatically generates custom pie charts from user-uploaded data.
- A personal finance tracker that uses an exploded pie chart to highlight your largest spending category.
Describe your application, and Replit Agent will write the code, handle testing, and deploy it for you. Start building your next data visualization tool with Replit Agent.
Common errors and challenges
When creating pie charts in Python, you might encounter a few common issues, but they are usually straightforward to resolve.
Fixing a mismatch between sizes and labels
A frequent error occurs when the number of elements in your sizes list doesn't match the number in your labels list. Matplotlib requires a one-to-one correspondence to know which label belongs to which slice. If they don't match, you'll get a ValueError, and your chart won't render. Always double-check that both lists have the same length before plotting.
Making pie charts more readable with too many small slices
Pie charts lose their effectiveness when you have too many small slices. The chart can become cluttered, and the labels may overlap, making it difficult to read. If you find yourself in this situation, consider these alternatives:
- Combine the smallest slices into a single "Other" category to simplify the visualization.
- Switch to a bar chart, which is often better for comparing the values of many different categories.
Ensuring proper circular display with plt.axis('equal')
Sometimes your pie chart might appear as an oval instead of a perfect circle. This distortion misrepresents the data by skewing the visual proportions of the slices. As mentioned earlier, you can easily fix this by adding plt.axis('equal') to your code, which ensures the chart maintains a circular aspect ratio.
Fixing a mismatch between sizes and labels
When you pass data to plt.pie(), it expects the sizes and labels lists to have the same number of items. If one is shorter, Python can't pair them up and will raise an error. The code below shows this exact scenario.
import matplotlib.pyplot as plt
sizes = [35, 25, 20, 20]
labels = ['Apples', 'Bananas', 'Oranges'] # Only 3 labels for 4 data points
plt.pie(sizes, labels=labels)
plt.show()
The plt.pie() function fails because it receives four values in the sizes list but only three strings in labels. This mismatch prevents it from assigning a name to every slice. The following code demonstrates the correct approach.
import matplotlib.pyplot as plt
sizes = [35, 25, 20, 20]
labels = ['Apples', 'Bananas', 'Oranges', 'Grapes'] # Now we have 4 labels
plt.pie(sizes, labels=labels)
plt.show()
The solution is to ensure the sizes and labels lists have an equal number of elements. By adding 'Grapes' to the labels list, it now matches the four data points in sizes, allowing Matplotlib to pair each value with a label correctly.
This error often pops up when you manually update data or when it's generated dynamically. It’s a good practice to quickly verify that your data and label lists match in length before plotting.
Making pie charts more readable with too many small slices
While pie charts excel at showing parts of a whole, they become less effective with too many slices. The visualization gets cluttered, labels often overlap, and comparing proportions becomes difficult. The code below demonstrates this issue with a ten-slice chart.
import matplotlib.pyplot as plt
sizes = [30, 20, 15, 10, 5, 5, 5, 5, 3, 2]
labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
plt.pie(sizes, labels=labels)
plt.show()
The sizes list contains several small values, which forces plt.pie() to create tiny, cramped wedges. This makes the chart difficult to interpret accurately. The code below shows how to solve this by tidying up the data.
import matplotlib.pyplot as plt
# Original data
sizes = [30, 20, 15, 10, 5, 5, 5, 5, 3, 2]
labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
# Combine small slices (less than 10) into "Other"
new_sizes = [30, 20, 15, 10, 20] # 20 is sum of all small slices
new_labels = ['A', 'B', 'C', 'D', 'Other']
plt.pie(new_sizes, labels=new_labels)
plt.show()
To fix a cluttered chart, you can group small slices into an "Other" category. The code does this by creating new_sizes and new_labels lists. It sums the values of all slices smaller than 10 and adds this total to new_sizes, while the corresponding new_labels list now includes an "Other" label. This declutters the visualization, making it easier to interpret. This is especially helpful when working with datasets that have many low-value entries.
Ensuring proper circular display with plt.axis('equal')
Your pie chart can sometimes appear as an oval instead of a circle, which misrepresents the data by skewing proportions. This happens when the plot's aspect ratio isn't equal. The code below demonstrates how a chart can look without this adjustment.
import matplotlib.pyplot as plt
sizes = [35, 25, 20, 20]
labels = ['Apples', 'Bananas', 'Oranges', 'Grapes']
plt.pie(sizes, labels=labels)
plt.show() # May appear as an oval rather than a circle
Without explicit instructions, Matplotlib may not render a perfect circle, leading to a skewed appearance. The following code shows how to correct this and ensure your chart is displayed accurately.
import matplotlib.pyplot as plt
sizes = [35, 25, 20, 20]
labels = ['Apples', 'Bananas', 'Oranges', 'Grapes']
plt.pie(sizes, labels=labels)
plt.axis('equal') # Ensures the pie is drawn as a circle
plt.show()
The solution is to add plt.axis('equal') right after your plt.pie() call. This function forces Matplotlib to use an equal aspect ratio, ensuring the chart is drawn as a perfect circle rather than a skewed oval. This distortion can happen if the figure's dimensions aren't square, so it's a good practice to always include this line to guarantee your data is represented accurately.
Real-world applications
Now that you can create and troubleshoot pie charts, you can visualize real-world data like expense distributions and programming language popularity.
Visualizing expense distribution with pie() charts
A pie chart offers an intuitive way to see how different spending categories make up your total monthly expenses.
import matplotlib.pyplot as plt
expenses = {'Rent': 1200, 'Food': 350, 'Utilities': 200, 'Entertainment': 150, 'Savings': 300}
labels = list(expenses.keys())
sizes = list(expenses.values())
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title('Monthly Expense Distribution')
plt.show()
This example starts by storing financial data in an expenses dictionary, a convenient way to keep categories and values paired. The code then efficiently prepares this data for plotting:
- It extracts the category names using
list(expenses.keys())to create thelabels. - It pulls the corresponding amounts with
list(expenses.values())to define thesizes.
The plt.pie() function then uses these lists to draw the chart, and plt.title() adds a clear heading before plt.show() renders the final visualization.
Analyzing programming language popularity with enhanced pie() charts
Applying enhancements like an exploded slice is a great way to visualize market share data, such as the popularity of different programming languages.
import matplotlib.pyplot as plt
languages = ['Python', 'Java', 'JavaScript', 'C++', 'Other']
usage = [45, 20, 15, 10, 10]
explode = [0.1, 0, 0, 0, 0] # Highlight Python
plt.pie(usage, labels=languages, explode=explode, shadow=True,
autopct='%1.1f%%', startangle=140)
plt.title('Programming Languages Popularity')
plt.show()
This code shows how to create a presentation-ready chart by mapping data from lists to visual elements. It combines several arguments in a single plt.pie() call to produce a polished result.
- The
languagesandusagelists provide the labels and proportional sizes for each slice. - The
explodelist corresponds to the data, using a non-zero value to offset the 'Python' slice and draw attention to it. - Other customizations, like the rotation from
startangleand theshadow, are passed directly into the function to complete the chart beforeplt.show()displays it.
Get started with Replit
Now, turn your knowledge into a real application. Describe what you want to build to Replit Agent, like "a tool to visualize stock portfolio allocation" or "an app that charts word frequency from a text file."
Replit Agent will write the code, handle testing, and deploy your application for you. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.


.png)
.png)