Skip to main content

Python Pie Chart: Build and Style with Pandas and Matplotlib

Learn how to build and enhance pie charts using Python’s Matplotlib and Pandas libraries. Discover practical code examples and essential design tips to create clear, readable visuals.
Apr 17, 2025  · 7 min read

Pie charts are one of the most popular plots for visualizing proportions. You will probably know them by now, but if you don’t, just imagine a big pie, or a round Swiss cheese, cut into slices of different sizes. 

Python offers multiple ways to create pie charts. In this tutorial, we will focus on how to create pie charts in Python using Matplotlib and Pandas, two of the most popular data analysis packages in Python. We will structure the article by method, so you can focus on the approach and syntax that fits better in your workflow. 

In addition to these methods, we will provide some tips to enhance the, troubleshooting, accessibility, and usability of pie charts. Finally, we will also consider other chart alternatives that may be more suitable than pie charts in certain scenarios.

Ways to Create Pie Charts in Python 

I’ll show you two different ways to create a Python pie chart, and you can decide for yourself which method you prefer. Both are popular and good options, so you can’t go wrong. 

Method 1: Pie charts with Matplotlib

Let’s start analyzing how to create a pie chart with Matplotlib. 

For this section, we will analyze data about the different courses available in the DataCamp course catalog, which you can find here. (I looked through the catalog and counted up the number of courses available in each technology and created a table with this info.)

How to create the chart

To create our first pie chart with Matplotlib, we can use the plt.pie() function. We will use a list of the number of courses available for different data and AI technologies (each representing the wedge size), as well as a second list containing the names of the technologies, which will be included in the chart using the labels parameter. Alternatively, we can use plt.legend() to add a separate legend.

As usual, don’t forget to run the plt.show() at the end of your code to display the Matplotlib plot correctly.

import pandas as pd
import matplotlib.pyplot as plt

courses = [164, 127, 31, 31,12, 11]
labels = ['Python','R','SQL','Power BI','Excel','ChatGPT']
dictionary = {'courses':courses, 'labels':labels}
python_pie_chart_df = pd.DataFrame(dictionary)

plt.pie(x = python_pie_chart_df.courses, labels = python_pie_chart_df.labels)
plt.show()

basic Python pie chart with a legend

plt.pie(x = python_pie_chart_df.courses)
plt.legend(labels = python_pie_chart_df.labels, loc = [0.95,0.35])
plt.show()

basic Python pie chart

Additionally, we could also include the percentage of each wedge using the autopct parameter. In the following example, we include the size of the wedges using one decimal.

plt.pie(x = python_pie_chart_df.courses, labels = python_pie_chart_df.labels, autopct='%1.1f%%') 
plt.show()

Python pie chart with labels

How to customize the chart

Pie charts in Matplotlib, as well as the slices that comprise them, are highly customizable. Let’s see some of the options that the pie.plot() function offers. 

To change the color of the slices, we can use the colors parameter. We will use this parameter to apply DataCamp’s color palette to our chart. 

datacamp_palette = ['#03ef62','#06bdfc','#ff6ea9','#ff931e','#ff5400','#7933ff']
plt.pie(x = python_pie_chart_df.courses, labels = python_pie_chart_df.labels, colors = datacamp_palette, autopct='%1.1f%%')
plt.show()

Python pie chart with custom color palette

Looks way better, right? But there’s much more we can do to customize our pie chart. For example, we can play with the distance of the labels and the percentages, using the labeldistance and pctdistance parameters, respectively, and choose an angle to start the slicing with the startangle parameter.

plt.pie(x = python_pie_chart_df.courses, labels = python_pie_chart_df.labels, colors = datacamp_palette, autopct='%1.1f%%', 
pctdistance= 0.8, labeldistance=1.1, startangle=180)

plt.show()

Finally, imagine you’re doing a presentation and want to focus on R courses. A handy way to highlight this is by exploding that wedge using the explode parameter, as follows:

explode = (0, 0.1, 0, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'R')

plt.pie(x = python_pie_chart_df.courses, labels = python_pie_chart_df.labels, 
        colors = datacamp_palette, autopct='%1.1f%%', 
        pctdistance= 0.8, labeldistance=1.1, 
        startangle=180, explode=explode)

plt.show()

How to save the chart

After you have created your pie chart, you are ready to share it with your collaborators. You can do this using the plt.savefig() function, which takes the file name as input to the function and allows you to save it in different formats, such as .png, .jpg, .svg, or .pdf. Additionally, you can use dpi to change the resolution of the image. 

Here is an example of how to save your pie plot in .jpg format with 200 dots per inch.

plt.pie(x = df.courses, labels = df.labels, 
        colors = datacamp_palette, autopct='%1.1f%%', 
        pctdistance= 0.8, labeldistance=1.1, 
        startangle=180, explode=explode)

plt.savefig('demo.jpg', dpi =200)

You can learn more about how to properly save visualization in our Introduction to Data Visualization with Matplotlib course.

Method 2: Pie charts with Pandas

Now that you know how to create a pie chart with Matplotlib, let’s see how it works in Pandas.

How to create the chart

Pandas has a plot() method that can be used to draw several types of plots. This method works on both the DataFrame and Series objects in Pandas. The kind argument in the plot() method can help you specify the type of plot. In our case, you can create a pie chart using kind ='pie'. You can also add the labels parameter to include a name in every wedge and the autopct parameter to add the percentages of each slice.

python_pie_chart_df['courses'].plot(kind='pie', labels=python_pie_chart_df['labels'], autopct='%1.1f%%')
plt.show()

How to customize the chart

Pandas' plot() method provides a tool for quick plotting but comes with limited customization options. Fortunately, the method uses Matplotlib as a backend, meaning that you can use Matplotlib syntax outside the method to customize your visualization. Below, you can find an example of how to combine Pandas and Matplotlib.

ax= python_pie_chart_df['courses'].plot(kind='pie', labels=python_pie_chart_df['labels'], autopct='%1.1f%%', 
                       colors=datacamp_palette, figsize=(5,5))

ax.set_title('Pie Chart DatataCamp Courses')
ax.set_ylabel(None)

plt.show()

How to save the chart

Saving pie charts in Pandas is exactly the same as in Matplotlib, as Pandas relies on Matplotlib under the hood.

ax= python_pie_chart_df['courses'].plot(kind='pie', labels=python_pie_chart_df['labels'], autopct='%1.1f%%', 
                       colors=datacamp_palette, figsize=(5,5))

ax.set_title('Pie Chart DatataCamp Courses')
ax.set_ylabel(None)

plt.savefig('demo.png')

Troubleshooting Pie Charts

To make sure your pie charts are displayed correctly, you must provide Matplotlib with the right data. That means you should always conduct data cleaning techniques in your dataframe, such as deleting null values with pd.dropna() and setting the right data types for your input columns.

Moreover, customization will be key in displaying a compelling and impactful pie chart. However, keep in mind that in case you’re using Pandas, advanced customizations like exploding may not be supported. As already mentioned, if you need more control over your pie chart, you may need to add Matplotlib code to your scripts.

Enhancing Accessibility and Usability

When displaying your pie charts, you should stick to good practices.

  • Assess your audience: As a golden rule, you should always empathize with the audience your visualization is addressing. This means having a good understanding of your audience’s area of expertise, level of technical knowledge, and interests. 
  • Clear the clutter: To avoid making unreadable, cluttered visualizations, ask yourself if what you’re including is relevant to the audience, and remove unnecessary elements as much as you can. In the case of pie charts, you should avoid 3D effects or shadows, as they may hinder interpretation. 
  • Keep an eye on the fonts: Even though it can be tempting to use different fonts and sizes, as a general rule of thumb, stick to one font with no more than three different sizes. You should follow the font hierarchy and keep headings larger than the body, as well as use a bold typeface to highlight key elements and headings. 
  • Use colors creatively: Color is one of the most eye-catching aspects of any data visualization. As such, put a lot of thought into choosing the color scheme of your data visualization. This means having a consistent color palette across your visualizations and using color systematically to distinguish between groups, levels of importance, and different kinds of information hierarchy.
  • Testing on other devices: It’s always good advice to test your visuals to see how they look on multiple devices.

Data visualization can be considered an art. Intuition and good taste can make a difference, but you should always consider the theory behind it. To know more about the best practices for effective data visualization, check out our Data Storytelling & Communication Cheat Sheet. Further, if you are working with dashboards, this article on Best Practices for Designing Dashboards is worth reading.

Alternatives to Pie Charts

Truth be told, pie charts are among the most criticized plots. It’s been demonstrated that humans are not very good at interpreting angles. We can illustrate this with the pie chart we have used before. Consider the slices of Excel and ChatGPT. Can you tell at first sight which one has the biggest angle?

Arguably not, and that’s why many data visualization experts recommend using other charts to depict proportions, especially when dealing with many categories, such as bar charts and stacked bar charts, treemaps, or even donut charts. You can learn more about these alternatives in our article Types of Data Plots and How to Create Them in Python.

Conclusion

Congratulations on making it to the end of the tutorial. Python is a highly versatile programming language, offering several libraries and approaches to create pie charts. In this tutorial, we analyze how to create pie charts with Matplotlib and Pandas. Both are equally suitable for the job and have notable similarities. The idea is not to choose one but to use them interchangeably, according to your needs and workflow. 

If you want to know more about pie charts and, more broadly, data visualization in Python, DataCamp is here to help you. Check out our dedicated materials to become and get ready to become a visualization wizard!


Javier Canales Luna's photo
Author
Javier Canales Luna
LinkedIn

I am a freelance data analyst, collaborating with companies and organisations worldwide in data science projects. I am also a data science instructor with 2+ experience. I regularly write data-science-related articles in English and Spanish, some of which have been published on established websites such as DataCamp, Towards Data Science and Analytics Vidhya As a data scientist with a background in political science and law, my goal is to work at the interplay of public policy, law and technology, leveraging the power of ideas to advance innovative solutions and narratives that can help us address urgent challenges, namely the climate crisis. I consider myself a self-taught person, a constant learner, and a firm supporter of multidisciplinary. It is never too late to learn new things.

FAQs

What is a pie chart, and when should I use it?

A pie chart is a type of graph in which a circle is divided into sectors that each represent a proportion of the whole. It’s then suitable for representing proportions.

How can I create a pie chart in Matplotlib?

The easiest way to create a pie chart with Matplotlib is with the plt.pie() function, which comes with various customization parameters.

How can I create a pie chart in Pandas?

The easiest way to create a pie chart with Matplotlib is with the Series.plot.(kind=’pie’) method. It allows quick visualization on Pandas DataFrames but has limited customization options compared to Matplotlib.

What are the best practices when creating pie charts?

You should always follow best practices to create your visualizations. That includes keeping your pie charts as simple as possible, avoiding unnecessary elements, choosing intuitive color palettes, and tailoring the plot according to your audience.

What are the main limitations of pie charts?

Humans are not very good at interpreting angles, that’s why many visualization expects recommend using other charts to visualize proportions, such as bar charts.

Topics

Learn with DataCamp

Course

Understanding Data Science

2 hr
732.3K
An introduction to data science with no coding involved.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

cheat-sheet

Matplotlib Cheat Sheet: Plotting in Python

This Matplotlib cheat sheet introduces you to the basics that you need to plot your data with Python and includes code samples.
Karlijn Willems's photo

Karlijn Willems

6 min

Tutorial

Python Bar Plot: Master Basic and More Advanced Techniques

Create standout bar charts using Matplotlib, Seaborn, Plotly, Plotnine, and Pandas. Explore bar chart types, from simple vertical and horizontal bars to more complex grouped and stacked layouts.
Samuel Shaibu's photo

Samuel Shaibu

7 min

Tutorial

Introduction to Plotting with Matplotlib in Python

This tutorial demonstrates how to use Matplotlib, a powerful data visualization library in Python, to create line, bar, and scatter plots with stock market data.

Kevin Babitz

12 min

Tutorial

Histograms in Matplotlib

Learn about histograms and how you can use them to gain insights from data with the help of matplotlib.
Aditya Sharma's photo

Aditya Sharma

8 min

Tutorial

How to Make a Gantt Chart in Python with Matplotlib

Learn how to make a Gantt chart in Python with matplotlib and why such visualizations are useful.
Elena Kosourova's photo

Elena Kosourova

10 min

Tutorial

How to Create a Histogram with Plotly

Learn how to implement histograms in Python using the Plotly data visualization library.
Kurtis Pykes 's photo

Kurtis Pykes

12 min

See MoreSee More