Pie Charts in Python. Creating Pie Charts in Python | by Sadrach Pierre, Ph.D. | Towards Data Science

A pie chart is a type of data visualization that is used to illustrate numerical proportions in data. The python library ‘matplotlib’ provides many useful tools for creating beautiful visualizations, including pie charts. In this post, we will discuss how to use ‘matplotlib’ to create pie charts in python.
Let’s get started!
For our purposes, we will be using the Netflix Movies and TV Shows data set, which can be found here.
To start, let’s read the data into a Pandas data frame;
import pandas as pd df = pd.read_csv("netflix_titles.csv")
Next, let’s print the first five rows of data using the ‘.head()’ method:
print(df.head())
As we can see, the data contains columns with various categorical values. Pie charts typically show relative proportions of different categories in a data set. For our pie chart visualizations, the ‘rating’, ‘country’ ,and ‘type’ columns are good examples of data with categorical values we can group and visualize.
To get an idea of the distribution in categorical values for these columns, we can use the ‘Counter’ method from the collections module. Let’s apply the ‘Counter’ method to the ‘type’ column:
from collections import Counterprint(Counter(df['type']))
Let’s also look at the ‘rating’ column:
print(Counter(df['rating']))
Now, let’s proceed by grouping our data by the number of values for each ‘type’ category:
title_type = df.groupby('type').agg('count')print(title_type)
Next, let’s import a few modules from ‘matplotlib’:
import matplotlib.ticker as tickerimport matplotlib.cm as cmimport matplotlib as mplfrom matplotlib.gridspec import GridSpecimport matplotlib.pyplot as plt
Now, let’s sort the indices and counts for our aggregated types:
type_labels = title_type.show_id.sort_values().index type_counts = title_type.show_id.sort_values()
We then specify the figure details:
plt.figure(1, figsize=(20,10)) the_grid = GridSpec(2, 2)
and specify the color map information:
cmap = plt.get_cmap('Spectral')colors = [cmap(i) for i in np.linspace(0, 1, 8)]
Finally, let’s plot our pie chart:
plt.subplot(the_grid[0, 1], aspect=1, title='Types of Netflix Titles')type_show_ids = plt.pie(type_counts, labels=type_labels, autopct='%1.1f%%', shadow=True, colors=colors)plt.show()
We see that most of the Netflix titles in this data set are movies. We can also generate a pie chart for the ratings. Let’s aggregate by rating:
title_rating = df.groupby('rating').agg('count')rating_labels = title_rating.show_id.sort_values().index rating_counts = title_rating.show_id.sort_values()
And plot our chart:
plt.figure(1, figsize=(40,20))the_grid = GridSpec(2, 2)cmap = plt.get_cmap('Spectral')colors = [cmap(i) for i in np.linspace(0, 1, 8)]plt.subplot(the_grid[0, 1], aspect=1, title='Ratings of Netflix Titles')type_show_ids = plt.pie(rating_counts, labels=rating_labels, autopct='%1.1f%%', shadow=True, colors=colors)plt.show()
We see ‘TV-14’ and ‘TV-MA’ are the most common ratings in the data. A drawback of pie charts is that they become less useful the more categories present within a column. For example, in our ratings pie chart the ‘G’, ‘NC-17’, and ‘UR’ ratings overlap which doesn’t look visually pleasing. You can imagine that this gets worse with an increasing number of categories. To resolve this, let’s define a function that calculate the 75th percentile and groups the lesser counts together in an ‘other’ category:
def group_lower_ranking_values(column):    rating_counts = df.groupby(column).agg('count')    pct_value = rating_counts[lambda x: x.columns[0]].quantile(.75)    values_below_pct_value = rating_counts[lambda x: x.columns[0]].loc[lambda s: s < pct_value].index.values    def fix_values(row):        if row[column] in values_below_pct_value:            row[column] = 'Other'        return row     rating_grouped = df.apply(fix_values, axis=1).groupby(column).agg('count')    return rating_grouped
We can now aggregate our data using this function:
rating_grouped = group_lower_ranking_values('rating')rating_labels = rating_grouped.show_id.sort_values().index rating_counts = rating_grouped.show_id.sort_values()
And plot the result:
plt.subplot(the_grid[0, 1], aspect=1, title='Rating of Netflix Titles')type_show_ids = plt.pie(rating_counts, labels=rating_labels, autopct='%1.1f%%', shadow=True, colors=colors)plt.show()
We see this looks much better than the previous plot. Let’s do the same for the country column. Here, we will consider the 99th percentile:
def group_lower_ranking_values(column):    ...    pct_value = rating_counts[lambda x: x.columns[0]].quantile(.99)    ...    return rating_groupedcountry_grouped = group_lower_ranking_values('country')country_labels = country_grouped.show_id.sort_values().index country_counts = country_grouped.show_id.sort_values()plt.subplot(the_grid[0, 1], aspect=1, title='Country of Netflix Titles')type_show_ids = plt.pie(country_counts, labels=country_labels, autopct='%1.1f%%', shadow=True, colors=colors)plt.show()
I’ll stop here but feel free to play around with the code yourself.
To summarize, in this post we discussed how to create pie charts in python. We showed to represent proportions of categories corresponding to title types, ratings and countries for Netflix titles. We also showed how to resolve the issue of visualizing a column with too many category types by calculating the highest ranking categories and grouping the lower values into a single ‘other’ group. I hope you found this post interesting/useful. The code from this post is available on GitHub. Thank you for reading!