您的当前位置:首页正文

箱型图大揭秘!Matplotlib带你玩转数据界的‘变形金刚’

2024-11-08 来源:个人技术集锦

1. 导包

# 导包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 如果浏览器不显示图片,就需要加上这句话
%matplotlib inline

# 让图片中可以显示中文
plt.rcParams['font.sans-serif'] = "SimHei"
# 让图片中可以显示负号
plt.rcParams["axes.unicode_minus"] = False

# 支持svg矢量图
%config Inlinebackend.figure_format = "svg"

2. 箱型图

x = [1, 2, 3, 5, 7, 9, 20, -10]
plt.boxplot(x)
plt.show()

# 异常值

# 最大值
# 3/4  Q3
# 2/4  中位数
# 1/4  Q1
# 异常值

# 异常值

3. 一次画多个箱型图

x1 = np.random.randint(10, 100, 100)
x2 = np.random.randint(10, 100, 100)
x3 = np.random.randint(10, 100, 100)

plt.boxplot([x1, x2, x3])
plt.show()

data = np.random.normal(size=(500, 4))
data
array([[-0.73374384,  0.63175711,  1.04054883, -0.43242146],
       [-0.28473971, -0.92793591,  0.43866245,  1.900678  ],
       [-0.89522388, -1.16235456, -1.12767215,  1.53754262],
       ...,
       [-0.29056696, -0.46957062,  0.51633617, -2.18227425],
       [-0.39322918,  0.17550912, -0.36366539, -2.10251157],
       [-1.26435622, -1.16706424,  0.69153696, -0.34231218]])
labels = ["A", "B", "C", "D"]
# labels:设置标签
# notch:箱型图样式
# sym:颜色和marker
plt.boxplot(data, labels=labels, notch=True, sym="r*")
plt.show()

显示全文