Matplotlib - Pie Chart



A pie chart is a circular graph that represents data in slices, where each slice corresponds to a category or portion of the whole. The size of each slice reflects the proportion of data it represents. It is a visual way to show how parts contribute to a whole.

Pie Chart

Pie Chart in Matplotlib

We can create a pie chart in Matplotlib using the pie() function. This function allows us to customize the appearance of the pie chart, including colors, labels, and the starting angle.

The pie() Function

The pie() function in Matplotlib takes an array or a list of values, where each value represents the size of a slice in the pie. The function provides visual proportions and distributions of categorical data in a circular format.

Following is the syntax of pie() function in Matplotlib −

plt.pie(x, explode=None, labels=None, colors=None, autopct=None, shadow=False, startangle=0)

Where,

  • x is an array or list of values representing the sizes of slices.
  • explode (optional) is an array or list specifying the fraction of the radius with which to offset each slice.
  • labels (optional) is the list of strings providing labels for each slice.
  • colors (optional) is list of colors for each slice.
  • autopct (optional) format string or function for adding percentage labels on the pie.
  • If shadow (optional) is True, it adds a shadow to the pie.
  • startangle (optional) is the angle by which the start of the pie is rotated counterclockwise from the x-axis.

These are just a few parameters; there are more optionals parameters available for customization.

Exploded Pie Chart

When creating an exploded pie chart, we separate one or more slices, "exploding" them away from the center of the chart. This highlights specific categories as we visually pull them away from the rest of the pie.

Example

In the following example, we are creating a pie chart to show proportions of categories like 'Category A', 'Category B', 'Category C', and 'Category D'. We are using the explode parameter to move the second slice ('Category B') away from the center by a distance of 0.1 times the radius −

import matplotlib.pyplot as plt

# Data for proportions
sizes = [20, 35, 25, 20]
explode = (0, 0.1, 0, 0)

# Creating an exploded pie chart
plt.pie(sizes, explode=explode, labels=['Category A', 'Category B', 'Category C', 'Category D'])
plt.title('Exploded Pie Chart')
plt.show()

Output

After executing the above code, we get the following output −

Exploded Pie Chart

Custom Colored Pie Chart

A custom-colored pie chart allows you to assign specific colors to different slices of the pie, adding a visually distinct touch to each category.

Example

In here, we are creating a pie chart to represent proportions of categories such as 'Category A', 'Category B', 'Category C', and 'Category D'. We are using the colors parameter to assign custom colors to each slice −

import matplotlib.pyplot as plt

# Data for proportions
sizes = [30, 20, 25, 25]
colors = ['gold', 'lightskyblue', 'lightcoral', 'lightgreen']

# Creating a custom colored pie chart
plt.pie(sizes, labels=['Category A', 'Category B', 'Category C', 'Category D'], colors=colors)
plt.title('Custom Colored Pie Chart')
plt.show()

Output

Following is the output of the above code −

Custom Colored Pie Chart

Example

Here, we enhance pie chart colors in Matplotlib by generating "n" data points randomly, setting the figure size and padding, then creating a pie chart subplot with varying colors using the pie() method −

import matplotlib.pyplot as plt
import random
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

n = 40
color = ["#" + ''.join([random.choice('0123456789ABCDEF')
                        for j in range(6)]) for i in range(n)]
a = np.random.random(n)
f = plt.figure()
ax = f.add_subplot(111, aspect='equal')
p = plt.pie(a, colors=color)

plt.show()

Output

Output of the above code is as shown below −

More Colors Pie Chart

Percentage-labeled Pie Chart

A percentage-labeled pie chart is a type of pie chart where we lable each slice with its percentage of the whole. This helps us by providing a clear understanding of the proportional contribution of each category.

Example

Now, we create a pie chart that represents the distribution of categories ('Category A', 'Category B', 'Category C', 'Category D'). We use the autopct='%1.1f%%' parameter to display the percentage contribution of each slice −

import matplotlib.pyplot as plt

# Data for proportions
sizes = [15, 30, 45, 10]

# Creating a pie chart with percentage labels
plt.pie(sizes, labels=['Category A', 'Category B', 'Category C', 'Category D'], autopct='%1.1f%%')
plt.title('Percentage-labeled Pie Chart')
plt.show()

Output

Output of the above code is as follows −

Percentage-labeled Pie Chart

Example

We can also show the percentage or proportional data where each slice of pie represents a category.

In here, we create a pie chart to show our daily activities, i.e. sleeping, eating, working, and playing. Using plt.pie() method, we create a pie chart with the given different data sets for different activities −

import matplotlib.pyplot as plt

days = [1, 2, 3, 4, 5]

sleeping = [7, 8, 6, 11, 7]
eating = [2, 3, 4, 3, 2]
working = [7, 8, 7, 2, 2]
playing = [8, 5, 7, 8, 13]
slices = [7, 2, 3, 13]
activities = ['sleeping', 'eating', 'working', 'playing']
cols = ['c', 'm', 'r', 'b']

plt.pie(slices,
   labels=activities,
   colors=cols,
   startangle=90,
   shadow=True,
   explode=(0, 0.1, 0, 0),
   autopct='%1.1f%%')

plt.title('Pie Plot')
plt.show()

Output

We get the output as shown below −

Categorical Pie Chart

Shadowed Pie Chart

A shadowed pie chart is a type of pie chart that includes a shadow effect, giving it a three-dimensional appearance. The shadows are generally projected to one side, creating a sense of depth and highlighting separation of each slice.

Example

In the example below, we are using the shadow=True parameter used to add a shadow effect to the chart, providing a visual depth that enhances the separation between slices −

import matplotlib.pyplot as plt
sizes = [25, 20, 30, 25]

# Creating a shadowed pie chart
plt.pie(sizes, labels=['Category A', 'Category B', 'Category C', 'Category D'], shadow=True)
plt.title('Shadowed Pie Chart')
plt.show()

Output

The output obtained is as shown below −

Shadowed Pie Chart
Advertisements