pythonic生物人

Python轻松添加统计P value(进阶版)

本节进一步讲解如何在组内和组间同时添加p值,并展示如何将图中的数值型p值转换为“*”或“ns”等符号形式进行表示。

p值和“*”或“ns”等符号对应关系:

  • ns: 5.00e-02 < p <= 1.00e+00
  • *: 1.00e-02 < p <= 5.00e-02
  • **: 1.00e-03 < p <= 1.00e-02
  • ***: 1.00e-04 < p <= 1.00e-03
  • ****: p <= 1.00e-04

使用diamonds数据集(详见“3.2.6 diamonds数据集”),比较钻石在不同“颜色”之间以及同一“颜色”内部,不同“切工”对“价格 ($)”是否存在显著差异。

# -*- encoding: utf-8 -*-
'''
未经过允许禁止转载!
@Author  :   公众号: pythonic生物人
'''

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

# 数据准备
diamonds = diamonds[diamonds["颜色"].isin(["E", "J", "D"])]

# 绘图
fig, axs = plt.subplots(2,
                        2,
                        figsize=(12, 8),
                        sharex=True,
                        sharey=True,
                        dpi=300)
fig.patch.set_edgecolor('gray')
fig.patch.set_linewidth(0.8)

handles, labels = None, None  # 提取第一个子图的图例
for i, ax in enumerate(axs.flatten()):
    sns.boxplot(
        data=diamonds,
        x="颜色",
        y="价格 ($)",
        hue="切工",
        palette=['#006a8e', '#b1283a', '#a8a6a7', "#d5695d", "#5d8ca8"],
        showfliers=False,
        ax=ax,
        width=0.8)

    if handles is None:
        handles, labels = ax.get_legend_handles_labels()  # 图例设置

    pairs = [
        (("E", "Premium"), ("E", "Fair")),  # 设置组内配对统计检验组合
        (("E", "Premium"), ("J", "Premium")),  # 设置组间配对统计检验组合
        (("J", "Ideal"), ("D", "Good"))  # 设置组间配对统计检验组合
    ]

    test_types = [
        "Mann-Whitney-ls", "t-test_ind", "Kruskal", "Brunner-Munzel"
    ]  # 设置四个不同的统计检验测试类型

    annotator = Annotator(
        ax,
        pairs,  #使用组内组间配对统计检验组合pairs
        data=diamonds,
        x="颜色",
        y="价格 ($)",
        hue="切工")
    annotator.configure(
        test=test_types[i],  # 设置当前子图的统计检验
        text_format="star",  #p value大小使用"*"或者"ns"表示
        line_width=1,  #组间或者组内连线宽度
        fontsize=20  ##p value的"*"或者"ns"字号
    )

    annotator.apply_and_annotate()

    ax.set_xlabel('')  # 隐藏x轴标题
    ax.set_ylabel('')  # 隐藏y轴标题

# 设置Figure的x轴和y轴标题
fig.text(0.5, -0.02, '颜色', ha='center', fontsize=14)
fig.text(-0.02, 0.5, '价格 ($)', va='center', rotation='vertical', fontsize=14)

# 添加共享图例
fig.legend(handles,
           labels,
           loc='right',
           ncol=5,
           bbox_to_anchor=(0.5, 1.0),
           fontsize=12)
for ax in axs.flatten():
    ax.legend_.remove()  #移除子图图例
plt.tight_layout(rect=[0, 0, 1, 0.96])
plt.show()

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