Python Matplotlib - How to create a Pie Chart in Matplotlib


 

Matplotlib provides support for pie charts using the pie() function. This module allows the creation of various types of graphs, including pie charts, which visually represent data proportions in a circular format.

Creating a simple Pie Chart

Below is an example of how to create a basic pie chart using Matplotlib:

Example: Simple Pie Chart

import matplotlib.pyplot as plt

# Data to plot
labels = ['Angola', 'Brazil', 'Portugal', 'Cape Verde']
sizes = [1215, 2130, 2245, 2210]

# Define colors for each segment
colors = ['lightcoral', 'gold', 'yellowgreen', 'lightskyblue']

# Explode the first slice
explode = (0.1, 0, 0, 0)  

# Create pie chart
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)

# Ensure the pie chart is a circle
plt.axis('equal')

# Display the chart
plt.show()

Explanation of the Code:

  • The labels list defines the names of the categories.
  • The sizes list specifies the values corresponding to each category.
  • The colors list determines the color of each segment.
  • The explode parameter offsets a selected slice from the center.
  • The autopct='%1.1f%%' argument adds percentage labels to each segment.
  • The shadow=True argument adds a shadow effect.
  • The startangle=140 rotates the chart for better visibility.
  • The plt.axis('equal') ensures the pie chart remains circular.

Adding a Legend to the Pie Chart

You can add a legend to indicate what each segment represents using the legend() function.

Example: Pie Chart with Legend

import matplotlib.pyplot as plt

# Data to plot
labels = ['Angola', 'Brazil', 'Portugal', 'Cape Verde']
sizes = [1215, 2130, 2245, 2210]

# Define colors for each segment
colors = ['lightcoral', 'gold', 'yellowgreen', 'lightskyblue']

# Explode the first slice
explode = (0.1, 0, 0, 0)  

# Create pie chart
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)

# Add legend
plt.legend(labels, loc="upper right")

# Ensure the pie chart is a circle
plt.axis('equal')

# Display the chart
plt.show()

Legend positioning options

The loc parameter defines the position of the legend. Possible values include:

  • best (automatically selects the best position)
  • upper right
  • upper left
  • lower left
  • lower right
  • center left
  • center right
  • lower center
  • upper center
  • center

Conclusion

Pie charts are an effective way to visualize proportions in a dataset. Using Matplotlib, you can customize the chart by adjusting slice sizes, labels, colors, explosion effects, and legend positions.