English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Matplotlib Pie Chart

The pie chart can only display a series of data. The pie chart displays the size of items in a data series (referred to as slices), proportional to the sum of the items. Data points in the pie chart are displayed as a percentage of the entire pie chart.

Matplotlib API has a pie() function that generates a pie chart representing the data in the array. The fractional area of each slice is determined by x/sum(x) gives. If sum(x<1Then the value of x is directly given as a decimal area, and the array will not be normalized. The resulting pie chart will have a size of1Empty slice - sum(x).

The pie chart looks best if the graph and axis are square, or if the axis directions are equal.

Parameters

The following table lists the parameters of the pie chart -

x - Array-like, slice sizes. labels - List. A series of strings, providing labels for each slice. colors - A series of matplotlib color parameters, the pie chart will cycle through them. If None, the colors from the current active cycle will be used. Autopct - string is used to label the slices. The labels will be placed inside the slices. The format string will be fmt%pct.

The following code uses the pie() function to display a pie chart of the list of students registered for the computer language course. The percentage is displayed inside the corresponding slice using the autopct parameter, which is set to %.1.2f%.

Example code:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
#! /usr/bin/env python
 #coding=utf-8
 import matplotlib.pyplot as plt
 import numpy as np
 import math
 plt.rcParams['font.sans']-serif'] = ['SimHei']  # Step one (replacement sans-serif font)
 plt.rcParams['axes.unicode_minus'] = False  # Original from [Lidi Huo], commercial redistribution please contact the author for authorization, non-commercial please retain the original link:
 fig = plt.figure()
 ax = fig.add_axes([0,0,1,1]
 ax.axis('equal')
 langs = ['C', 'C++', 'Java', 'Python', 'PHP']
 students = [23,17,35,29,12]
 ax.pie(students, labels = langs, autopct='%')1.2f%%')
 plt.show()

Execute the above example code to get the following results -