无法播放?请 点击这里 跳转到Youtube
切换视频源:

上一章我们学习了面积图,本章来学习箱形图和饼图,首先导入库:

import matplotlib.pyplot as plt
import numpy as np

箱形图 Box

箱形图是一种用于显示一组数据分布情况的统计图,它能显示出一组数据的最大值、最小值、中位数及上下四分位数。

在matplotlib中画箱形图很简单,只需要使用boxplot函数即可。如下我们为四组随机数创建箱形图,每组数据对应的标记为Label1到Label4:

fig, axe = plt.subplots(figsize = (8, 5))

np.random.seed(66)
labels = ["Label1", "Label2", "Label3", "Label4"]
values = []
values.append(np.random.normal(100, 20, 200)) # mean = 100, std = 20 for 200 values
values.append(np.random.normal(100, 100, 200))
values.append(np.random.normal(150, 50, 200))
values.append(np.random.normal(150, 70, 200))

axe.boxplot(values, labels=labels)
plt.show()

如果想要横向显示箱形图,我们只需将boxplot函数中的vert参数设为False:

fig, axe = plt.subplots(figsize = (8, 5))
axe.boxplot(values, labels=labels, vert=False)
plt.show()

我们也能通过设定其他的参数,对箱形图进行更多自定义。如下我们用蓝绿色填充中间的盒子,并将边缘色设为红色:

fig, axe = plt.subplots(figsize = (8, 5))
axe.boxplot(values, labels=labels,patch_artist=True, # 使用颜色填充
            boxprops=dict(facecolor='teal', color='r'))
plt.show()

饼图 Pie

饼图是一个划分为多个扇形的统计图表,在饼图中,每个扇形的弧长大小,表示该种类占总体的比例,这些扇形合在一起刚好是一个完全的圆形。

在matplotlib中可以用pie函数画饼图,只需要定义好每组数据的标记(labels)和数量(values)即可:

fig, axe = plt.subplots(figsize = (8, 5))

labels = ["P1", "P2", "P3", "P4", "P5", "P6"]
values = [200, 300, 88, 66, 110, 168]
axe.pie(values, labels=labels)

plt.show()

如果想要在饼图中显示每组数组所占的百分比,那么定义好autopct参数就好了:

fig, axe = plt.subplots(figsize = (8, 5))
axe.pie(values, labels=labels, autopct='%.2f%%') # 显示小数点后两位
plt.show()

若要在图中突出特定数据,我们可将每组数据的偏移值传入explode参数实现:

fig, axe = plt.subplots(figsize = (8, 5))

labels = ["P1", "P2", "P3", "P4", "P5", "P6"]
values = [200, 300, 88, 66, 110, 168]
explode = [0,0,0,0.4,0,0.1]
axe.pie(values, labels=labels, autopct='%.2f%%', explode = explode)

plt.show()

有时,我们想要比较多个数据集,比如在同一个图中画两个饼图,一个在外圈,一个在内圈,那么我们直接执行两次pie即可,并定义好每个饼图的半径radius:

fig, axe = plt.subplots(figsize = (8, 5))

labels = ["P1", "P2", "P3", "P4", "P5", "P6"]
labels2 = ["S1", "S2", "S3"]
values = [200, 300, 88, 66, 110, 168]
values2 = [500, 100, 200]
explode = [0,0,0,0.3,0,0]
explode2 = [0, 0.1, 0]

# outer circle
# pctdistance is used to control the distance between the center of the circle and percentage value.
# labeldistance is used to control the distance between the center of the circle and the label.
axe.pie(values, radius=1.5, wedgeprops=dict(width=0.5), autopct='%.2f%%', 
        pctdistance=0.8, labels=labels, labeldistance=1.05, explode=explode)
# inner circle
axe.pie(values2, radius=1, wedgeprops=dict(width=0.5), autopct='%.2f%%', 
        pctdistance=0.8, labels=labels2, labeldistance=0.3, explode=explode2)
plt.show()

这就是箱形图和饼图相关的内容啦,下一章我们来学习热图和3D图。