可视化库-Matplotlib-盒图(第四天)

盒图由五个数值点组成,最小观测值,下四分位数,中位数,上四分位数,最大观测值

IQR = Q3 - Q1  Q3表示上四分位数, Q1表示下四分位数,IQR表示盒图的长度

最小观测值 min =Q1 - 1.5*IQR

最大观测值 max=Q3 + 1.5*IQR  , 大于最大值或者小于最小值就是离群点

1. 画出一个盒图 plt.boxplot(tang_array, notch=False, sym='o', vert=True)  #  tang_array表示输入的列表, notch表示盒图的样子,sym表示偏离值的表示方法, vert表示竖着,还是横着

import matplotlib.pyplot as plt
import numpy as np
# 构造正态分布的列表数组
tang_array = [np.random.normal(0, std, 100) for std in [0.1, 0.2, 0.3, 0.4]]

fig = plt.figure(figsize=(8, 6))
plt.boxplot(tang_array, notch=False, sym='o', vert=True)

plt.xticks([x+1 for x in range(len(tang_array))], ['x1', 'x2', 'x3', 'x4'])
plt.title('box plot')
plt.xlabel('x')
plt.show()

2  设置盒图的线条颜色

import matplotlib.pyplot as plt
import numpy as np
# 构造正态分布的列表数组
tang_array = [np.random.normal(0, std, 100) for std in [0.1, 0.2, 0.3, 0.4]]

fig = plt.figure(figsize=(8, 6))
bplt = plt.boxplot(tang_array, notch=False, sym='o', vert=True)
for compnent  in bplt.keys():
    for line in bplt[compnent]:
        line.set_color('red')

plt.xticks([x+1 for x in range(len(tang_array))], ['x1', 'x2', 'x3', 'x4'])
plt.title('box plot')
plt.xlabel('x')
plt.show()

3.对盒图进行填充操作  设置pacth_artist=True 对盒图面进行填充bplt['boxes'].set_facecolor('r')

tang_array = [np.random.uniform(0, std, 100) for std in [0.1, 0.2, 0.3, 0.4]]
bar_labels = ['x1', 'x2', 'x3', 'x4']

fig = plt.figure()
plt.xticks([x+1 for x in range(len(tang_array))], bar_labels)
bplt = plt.boxplot(tang_array, notch=False, sym='o', vert=True, patch_artist=True)

colors = ['pink', 'lightblue', 'lightgreen']
for pacthes, color in zip(bplt['boxes'], colors):
    pacthes.set_facecolor(color)

plt.show()

4. 设置小提琴图

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 5))
tang_data = [np.random.normal(0, std, 100) for std in range(1, 4)]
axes[0].violinplot(tang_data, showmeans=False, showmedians=True)
axes[0].set_title('violin plot')

axes[1].boxplot(tang_data)
axes[1].set_title('box plot')


for ax in axes:
    # 对y轴加上网格
    ax.yaxis.grid(True)
    ax.set_xticks([y+1 for y in range(len(tang_data))])
# 对每个图加上xticks操作
plt.setp(axes, xticks=[y+1 for y in range(len(tang_data))], xticklabels=['x1', 'x2', 'x3'])
plt.show()

猜你喜欢

转载自www.cnblogs.com/my-love-is-python/p/10238327.html