Matplotlib 简明教程

Matplotlib - Pie Chart

饼图只能显示一个数据系列。饼图显示了一个数据系列中各个项目(称为饼片)的大小,与各个项目总数成比例。饼图中的数据点显示为整个饼图中的百分比。

A Pie Chart can only display one series of data. Pie charts show the size of items (called wedge) in one data series, proportional to the sum of the items. The data points in a pie chart are shown as a percentage of the whole pie.

Matplotlib API 有一个 pie() 函数,该函数生成一个饼图,表示数组中的数据。每个饼片的部分面积由 x/sum(x) 给出。如果 sum(x)< 1,那么 x 的值将直接给出部分面积,并且数组不会规范化。生成的饼将包含大小为 1 - sum(x) 的空白饼片。

Matplotlib API has a pie() function that generates a pie diagram representing data in an array. The fractional area of each wedge is given by x/sum(x). If sum(x)< 1, then the values of x give the fractional area directly and the array will not be normalized. Theresulting pie will have an empty wedge of size 1 - sum(x).

如果图形和坐标轴为方形,或者坐标轴的纵横比相等,则饼图看起来效果最佳。

The pie chart looks best if the figure and axes are square, or the Axes aspect is equal.

Parameters

下表列出了饼图的参数 −

Following table lists down the parameters foe a pie chart −

x

array-like. The wedge sizes.

labels

list. A sequence of strings providing the labels for each wedge.

Colors

A sequence of matplotlibcolorargs through which the pie chart will cycle. If None, will use the colors in the currently active cycle.

Autopct

string, used to label the wedges with their numeric value. The label will be placed inside the wedge. The format string will be fmt%pct.

以下代码使用 pie() 函数来显示注册各种计算机语言课程的学生列表的饼图。比例百分比显示在相应饼片内,这借助于 autopct 参数实现,该参数设置为 %1.2f%。

Following code uses the pie() function to display the pie chart of the list of students enrolled for various computer language courses. The proportionate percentage is displayed inside the respective wedge with the help of autopct parameter which is set to %1.2f%.

from matplotlib import pyplot as plt
import numpy as np
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()
pie chart