Pie Charts
DS 2023 | Communicating with Data

Overview¶
A pie chart is a circular graph used to display the relative magnitudes of a numeric measurement variable associated with a grouping variable.
For example, a grouping variable might be the types of food eaten during a day and the associated measurement might be number of calories.
The entire circle represents sum total of value of a given measurement, e.g. the total number of calories consumed in a day.
Each slice represents the contribution to the total by one of the group’s categories.
The area of the wedge is proportional to the magnitude of the measurement value for the category.
Pie charts typically use color to distinguish the different slices.
Use Cases¶
Viewing grouping variables whose domains constitute some whole, for example food types and diets, expenses and budgets, or investment options and portfolios.
Representing aggregate values for the domain of a grouping variable, where each slice represents a unique value and an associated statistic, such as its count or mean.
A simple example¶
Let’s create some imaginary data based the already described example — someone’s nutrient consumption in the course of a day by food type and measured in grams.
The pie will represent the total number of grams of food consumed by some person in a given day.
Each slice will represent on of the main nutrient groups — protein, fat, and carbohydrates.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as snsdiet = pd.Series({
'protein': 65,
'fat': 40,
'carbs': 18
})diet.plot.pie()
plt.show()
With this pie chart, we can see clearly the relative amounts consumed from each food type.
The person appears to be on a low-carb diet.
A more complex example¶
Let’s now look at a classic data set — the Titanic data set.
This data set shows the survival rate of passengers on the ill-fated vessel that sank in 1912.
It consists almost entirely of nominal data for 891 passengers.
These data are ideal for pie charts because:
Many variables represent exhaustive and exclusive groups, e.g.
classandsex.The number of values per feature is small.
We can use pie charts to display each feature’s composition.
titanic = sns.load_dataset('titanic')
titanic.sample(10)For convenience, let’s create a new feature age_group based on age to show if the person is an adult or child.
The converts the numberic variable age into a binary group.
titanic['age_group'] = np.where(
(titanic['age'] >= 18)
| titanic['who'].isin(['man','woman']),
'adult', 'child')In addition, we are only interested in a subset of categorial columns, those that meet the criteria specified above, so we select those.
my_cols = ['sex', 'age_group', 'class','survived']
titanic = titanic[my_cols]
titanic.sample(10)Now let’s create a pie chart for each of these features.
To do this, we create a list of aggregate data frames, one associated with each feature.
This is necessary because the slices of a pie chart must represent distinct categories.
dfs = {}
for col in my_cols:
dfs[col] = titanic.value_counts(col)for col in dfs:
df = dfs[col]
df.plot.pie(title=col.title(), figsize=(2,2))
plt.show()



A better way to show all for four pies is with a grid of subplots.
fig, ax = plt.subplots(2, 2, figsize=(6,6))
for i, col in enumerate(titanic.columns):
c = i % 2
r = i // 2
df = titanic.value_counts(col)
df.plot.pie(title=col.title(), ax=ax[r,c])
plt.show()
Combining groups¶
We can see that there are two kinds of group variables in the Titanic data set:
those that define the social category of each person
one that defines the fate each person.
The first set may be thought of as input values and the second as the output.
Let’s group the data by social category and get the value counts of the survival variable.
This produces a data frame where the categorical features form the index and the survival feature is projected onto the column axis.
titanic_vc = titanic[my_cols].value_counts().unstack(fill_value=0)
titanic_vc.columns = ['no','yes']
titanic_vcWe can use the survival rate data to compute a rough probability estimate s_rate as follows.
# titanic_vc['s_rate'] = titanic_vc.div(titanic_vc.sum(axis=1), axis=0).yes
titanic_vc['s_rate'] = titanic_vc['yes'] / titanic_vc[['no','yes']].sum(axis=1)
titanic_vc.sort_values('s_rate')In this form, the table lets us ask questions like:
“If a passenger was a first class adult male, what was their chance of surviving?”
Since these data are exhaustive, exclusive, and relatively few, we can use a pie chart to visualize the probabilities.
titanic_vc.s_rate.sort_values().plot.pie(title="Survival Rates")
plt.show()
How readable is this chart? Does it easily show which category combinations had the highest and lowest survival rates?
It turns out that pie charts become less useful as the number of categories increases.
In such cases, it is often better to fall back onto a bar chart.
The one below clearly shows which categories had the highest and lowest survival rates.
ax = titanic_vc.s_rate.sort_values().plot.barh()
plt.show()
(
titanic_vc
.query("age_group == 'adult'")
.s_rate
.sort_values()
.plot
.pie(title="Survival Rates of Adults")
)
plt.show()
Improving display¶
Panda’s pie charts come with some useful arguments to improve their display.
These are:
autopct: to label slices with their associated percentages.explode: to pull out a slide for emphasis.startangle: to orient the pie so that the first cut appears at the degree of your choice.
To use the autopct argument, you can pass a standard Python formatting string to autopct to control decimal places.
autopct='%1.1f%%': Displays one decimal place (e.g., ).autopct='%1.2f%%': Displays two decimal places (e.g., ).autopct='%1.0f%%': Rounds to the nearest whole integer (e.g., )
feature_name = 'survived'
dfs[feature_name].plot.pie(autopct='%1.2f%%', title=feature_name.title())
plt.show()
Here’s how you can pull out a slide to emphasize it.
explode_tuple = (0, 0.1, 0)
dfs['class'].plot.pie(autopct='%1.2f%%', explode=explode_tuple)
plt.show()
Note that you can pull out more than one slice.
explode_tuple = (0.1, 0.1, 0.1)
dfs['class'].plot.pie(autopct='%1.2f%%', explode=explode_tuple)
plt.show()
Finally, here’s how you can reorient the pie using startangle.
Here we set the value to , which corresponses to the 12:00 position of a clock.
dfs['class'].plot.pie(autopct='%1.2f%%', startangle=90)
plt.show()