分布(三)利用python绘制箱线图

分布(三)利用python绘制箱线图

箱线图 (Boxplot)简介

1

箱线图也叫盒须图,主要用来突出显示数据分布的四分位数。同时也可以获取较多的统计信息,例如:四分位数、异常值、分布是否倾斜/对称等。

快速绘制

  1. 基于seaborn

    import seaborn as sns
    import matplotlib.pyplot as plt
    sns.set(style="darkgrid")
    
    # 导入数据
    df = sns.load_dataset('iris')
    
    # 利用boxplot函数绘制箱线图
    sns.boxplot(y=df["sepal_length"])
    plt.show()
    

    2

定制多样化的箱线图

自定义箱线图一般是结合使用场景对相关参数进行修改,并辅以其他的绘图知识。参数信息可以通过官网进行查看,其他的绘图知识则更多来源于实战经验,大家不妨将接下来的绘图作为一种学习经验,以便于日后总结。

seaborn主要利用boxplot箱线图,可以通过seaborn.boxplot了解更多用法

  1. 绘制多个箱线图

    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.set(font='SimHei', font_scale=0.8, style="darkgrid") # 解决Seaborn中文显示问题
    
    # 导入数据
    df = sns.load_dataset('iris')
    df_tips = sns.load_dataset('tips')
    
    # 创建matplotlib的fig对象和子图对象ax
    fig, ax = plt.subplots(1,3, figsize=(12,4))
    
    # 多个数值变量的箱线图
    sns.boxplot(data=df.loc[:, ['sepal_length', 'sepal_width']], ax=ax[0]) 
    ax[0].set_title('多个数值变量')
    
    # 一个数值变量多个分组的箱线图
    sns.boxplot(x=df["species"], y=df["sepal_length"], ax=ax[1])
    ax[1].set_title('一个数值变量多个分组')
    
    # 一个数值变量多个分组子分组的箱线图
    sns.boxplot(x="day", y="total_bill", hue="smoker", data=df_tips, palette="Set1", width=0.5, ax=ax[2])
    ax[2].set_title('一个数值变量多个分组/子分组')
    
    # 调整间距并展示
    plt.tight_layout()
    plt.show()
    

    3

  2. 自定义箱线图

    • 自定义形状
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.set(font='SimHei', font_scale=0.8, style="darkgrid") # 解决Seaborn中文显示问题
    
    # 导入数据
    df = sns.load_dataset('iris')
    
    # 构造子图
    fig, ax = plt.subplots(1,3,constrained_layout=True, figsize=(12, 4))
    
    # 自定义线宽
    ax_sub = sns.boxplot(x=df["species"], y=df["sepal_length"], linewidth=5, ax=ax[0])
    ax_sub.set_title('自定义线宽')
    
    # 添加缺口
    ax_sub = sns.boxplot(x=df["species"], y=df["sepal_length"], notch=True, ax=ax[1])
    ax_sub.set_title('添加缺口')
    
    # 自定义箱体
    ax_sub = sns.boxplot(x=df["species"], y=df["sepal_length"], width=0.3, ax=ax[2])
    ax_sub.set_title('自定义箱体大小')
    
    plt.show()
    

    4

    • 自定义颜色
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.set(font='SimHei', font_scale=0.8, style="darkgrid") # 解决Seaborn中文显示问题
    
    # 导入数据
    df = sns.load_dataset('iris')
    
    # 构造子图
    fig, ax = plt.subplots(1,4,constrained_layout=True, figsize=(12, 4))
    
    # 分配调色板
    ax_sub = sns.boxplot(x=df["species"], y=df["sepal_length"], palette="Blues", ax=ax[0])
    ax_sub.set_title('分配调色板')
    
    # 统一颜色
    ax_sub = sns.boxplot(x=df["species"], y=df["sepal_length"], color='skyblue', ax=ax[1])
    ax_sub.set_title('统一颜色')
    
    # 自定义颜色
    my_pal = {"versicolor": "g", "setosa": "b", "virginica":"m"}
    ax_sub = sns.boxplot(x=df["species"], y=df["sepal_length"], palette=my_pal, ax=ax[2])
    ax_sub.set_title('指定颜色')
    
    # 突出颜色:针对指定组
    my_pal = {species: "r" if species == "versicolor" else "b" for species in df.species.unique()}
    ax_sub = sns.boxplot(x=df["species"], y=df["sepal_length"], palette=my_pal, ax=ax[3])
    ax_sub.set_title('突出颜色')
    
    plt.show()
    

    5

    • 自定义顺序
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.set(font='SimHei', font_scale=0.8, style="darkgrid") # 解决Seaborn中文显示问题
    
    # 导入数据
    df = sns.load_dataset('iris')
    
    # 构造子图
    fig, ax = plt.subplots(1,2,constrained_layout=True, figsize=(8, 4))
    
    # 指定顺序
    ax_sub = sns.boxplot(x='species', y='sepal_length', data=df, order=["versicolor", "virginica", "setosa"], ax=ax[0])
    ax_sub.set_title('指定顺序')
    
    # 按统计量降序:中位数
    my_order = df.groupby(by=["species"])["sepal_length"].median().iloc[::-1].index
    ax_sub = sns.boxplot(x='species', y='sepal_length', data=df, order=my_order, ax=ax[1])
    ax_sub.set_title('中位数降序')
    
    plt.show()
    

    6

  3. 添加额外数据信息

import seaborn as sns
import matplotlib.pyplot as plt

sns.set(font='SimHei', font_scale=0.8, style="darkgrid") # 解决Seaborn中文显示问题

# 导入数据
df = sns.load_dataset('iris')

# 构造子图
fig, ax = plt.subplots(1,2,constrained_layout=True, figsize=(8, 4))

# 1、添加数据点分布
ax_sub = sns.boxplot(x='species', y='sepal_length', data=df, ax=ax[0])
ax_sub = sns.swarmplot(x='species', y='sepal_length', data=df, color="grey", ax=ax[0])
ax_sub.set_title('添加数据点分布')

# 2、添加观测数量(避免过多信息造成视觉影响)
ax_sub = sns.boxplot(x='species', y='sepal_length', data=df, ax=ax[1])

medians = df.groupby(['species'])['sepal_length'].median().values
nobs = df['species'].value_counts().values
nobs = [str(x) for x in nobs.tolist()]
nobs = ["n: " + i for i in nobs]

pos = range(len(nobs))
for tick,label in zip(pos,ax_sub.get_xticklabels()):
    ax_sub.text(pos[tick],
            medians[tick] + 0.03,
            nobs[tick],
            horizontalalignment='center',
            size='x-small',
            color='w',
            weight='semibold')
ax_sub.set_title('添加观测数量')

plt.show()

7

总结

以上通过seaborn的boxplot可以快速绘制箱线图,并通过修改参数或者辅以其他绘图知识自定义各种各样的箱线图来适应相关使用场景。

共勉~

  • 18
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
箱线图是一种用于展示定量数据分布情况的图表,它呈现了一组数据的中位数、上下四分位数、极值和异常值。箱线图绘制可以使用Python中的Matplotlib库,以下是一个例子: 引用: Python matplotlib箱线图设置颜色 ```python import matplotlib.pyplot as plt list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] c_list = ['#ef476f', '#ffd166', '#118AD5'] # 颜色代码列表 # 绘制箱线图 f = plt.boxplot(list1, vert=True, sym='+b', showmeans=True, meanline=True, patch_artist=True, widths=0.2) for box, c in zip(f['boxes'], c_list): # 对箱线图设置颜色 box.set(color=c, linewidth=2) box.set(facecolor=c) plt.show() ``` 在这个例子中,我们使用了一个二维列表`list1`来存储数据,并使用`boxplot()`函数绘制箱线图。通过传递参数`vert=True`,我们将箱线图垂直绘制。参数`sym`定义了异常值的样式,参数`showmeans`和`meanline`分别控制了是否显示均值和均值线。参数`patch_artist=True`使得箱线图填充颜色,我们使用变量`c_list`来存储了种不同的颜色,之后我们使用`zip()`函数将`boxes`和`c_list`打包成元组,然后使用`set()`函数为每个箱子分配颜色。 引用: 利用Python – Matplotlib 绘制箱线图 如果想自己编写绘制箱线图的代码,可以按照以下步骤进行: 1. 计算数据的基本统计信息,包括中位数、上四分位数、下四分位数和极值。 2. 计算四分位数差,即上四分位数和下四分位数之差。 3. 计算箱线图的上下边界,即上限为上四分位数加上1.5倍的四分位数差,下限为下四分位数减去1.5倍的四分位数差。同时,将箱体的高度设置为四分位数差。 4. 绘制箱线图,包括中位数线、上下边界和箱体。 5. 可选地,将异常值标记出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值