pythonic生物人

Python轻松添加统计P value!


p value 是统计学中用于检验假设显著性的一个指标,常被用于判断结果是否具有统计意义。它在包括生物学、医学、社会科学等许多领域的数据分析中具有重要作用。

本次利用iris数据集(详细介绍见上文“3.2.8 iris数据集”),使用python seaborn箱图(详细介绍见上文“9.1.1 箱形图”)结合抖动散点图(详细介绍见上文“9.2.1 抖动散点图”),然后添加_p value。

以下使用8种不同检验方法("t-test_ind", "t-test_welch", "t-test_paired", "Mann-Whitney", "Mann-Whitney-gt", "Mann-Whitney-ls", "Levene", "Wilcoxon", "Kruskal","Brunner-Munzel"。)计算的 p value 值效果如下图,

Image
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from statannotations.Annotator import Annotator

colors = {"setosa": "#006a8e", "versicolor": "#b1283a", "virginica": "#a8a6a7"}
fig, axs = plt.subplots(
    5,
    2,
    figsize=(16, 25),
    sharex=True,  
    sharey=True, 
    dpi=300)
fig.patch.set_edgecolor('gray')
fig.patch.set_linewidth(2)

for i, ax in enumerate(axs.flatten()):
    sns.boxplot(data=iris,
                x="鸢尾花种类",
                y="花萼宽度 (cm)",
                ax=ax,
                showcaps=False,
                boxprops={'facecolor': 'none'},
                whiskerprops={'linewidth': 0},
                width=0.4)  # 绘制箱图
    sns.stripplot(data=iris,
                  x="鸢尾花种类",
                  y="花萼宽度 (cm)",
                  ax=ax,
                  size=8,
                  jitter=True,
                  edgecolor="black",
                  linewidth=0.8,
                  palette=colors,
                  alpha=0.9)  # 绘制随机抖动散点图

    pairs = [("setosa", "virginica"), ("setosa", "versicolor"),
             ("virginica", "versicolor")]  # 显著性检验组对
    test_types = [
        "t-test_ind", "t-test_welch", "t-test_paired", "Mann-Whitney",
        "Mann-Whitney-gt", "Mann-Whitney-ls", "Levene", "Wilcoxon", "Kruskal",
        "Brunner-Munzel"
    ]  # 设置不同的test参数,并在不同的子图上展示
    annotator = Annotator(ax, pairs, data=iris, x="鸢尾花种类", y="花萼宽度 (cm)")
    annotator.configure(
        test=test_types[i],  
        text_format="simple",
        line_width=1,
        fontsize=12)
    annotator.apply_and_annotate()

    ax.set_title(f"统计检验方法: {test_types[i]}",
                 fontsize=16,
                 fontweight="bold",
                 color='red')  
    ax.set_xlabel('')  
    ax.set_ylabel('')  

fig.text(0.5, -0.02, '鸢尾花种类', ha='center', fontsize=16)  # 设置Figure的x轴标题
fig.text(-0.02,
         0.5,
         '花萼宽度 (cm)',
         va='center',
         rotation='vertical',
         fontsize=16)  # 设置Figure的y轴标题

plt.tight_layout(rect=[0, 0, 1, 0.96])
plt.show()


更详细代码已添加到教程中:
👉《Python可视化教程》,优惠中!