You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python绘制的箱形图或小提琴图中添加p值标注

代码修改方案

你可以按照以下内容修改代码,实现添加组间差异显著性标注的需求,我们选择适配性更高的韦尔奇t检验计算组间p值,完全匹配你提供的显著性标识转换规则。

核心改动说明

  • 新增p值转显著性标记的工具函数,完全复用你给出的判断逻辑
  • 新增两两样本组合的p值计算逻辑,也支持自定义指定需要对比的样本对
  • 新增显著性标注的绘图逻辑,自动调整标注高度避免重叠
  • 原有数据处理、小提琴图绘制逻辑完全保留

完整修改后代码

#!/usr/bin/env python
"""
Usage: Run script in ~/snakemake_eclip/scripts, use help function to see which parameters are needed.
This script takes in the all_reads_matrix made by merge_matrix.py and creates a violin plot.
"""
import pandas as pd
import argparse
import matplotlib.pyplot as plt
import os
import seaborn as sns
import numpy as np
plt.switch_backend('agg')
from scipy import stats
from itertools import combinations # 新增导入,用于生成两两比较组合

def make_violin(in_matrix, save_path):
    df = pd.read_csv(str(in_matrix), index_col=False)
    # remove outliers
    Q1 = df.quantile(0.25)
    Q3 = df.quantile(0.75)
    IQR = Q3 - Q1
    df = df[~((df < (Q1 - 1.5 * IQR)) | (df > (Q3 + 1.5 * IQR))).any(axis=1)]
    # drop zeros
    df = df[(df != 0).all(1)]
    df = df.iloc[:, 1:].transform(lambda x: np.log(x / x.sum()))
    print(df)

    plt.figure(figsize=(20, 10), dpi=300)
    sns.violinplot(data=df)

    # ---------- 新增:组间差异p值计算与标注开始 ----------
    # 定义p值转显著性标识函数,完全匹配你提供的逻辑
    def get_p_sign(p):
        if p >= 0.05:
            return 'n.s.'
        elif p < 0.0001:
            return '***'
        elif p < 0.001:
            return '**'
        else:
            return '*'

    # 获取样本x轴位置
    sample_num = len(df.columns)
    x_pos = list(range(sample_num))
    # 设定标注起始高度,取数据集最大值往上5%的位置
    y_max = df.max().max()
    y_start = y_max + (y_max * 0.05)
    # 每组标注的高度增量,避免重叠
    y_step = (y_max - df.min().min()) * 0.08

    # 生成所有两两比较组合,不需要全量比较可自定义为类似[(0,1), (0,2)]的格式,数字对为x轴样本的索引
    compare_pairs = list(combinations(x_pos, 2))

    for idx, (x1, x2) in enumerate(compare_pairs):
        # 计算两组t检验p值
        group1 = df.iloc[:, x1].values
        group2 = df.iloc[:, x2].values
        t_stat, p_val = stats.ttest_ind(group1, group2, equal_var=False)
        sign = get_p_sign(p_val)
        # 当前标注的y坐标
        current_y = y_start + idx * y_step
        # 绘制两组之间的连接横线
        plt.plot([x1, x1, x2, x2], [current_y, current_y + y_step*0.1, current_y + y_step*0.1, current_y], lw=1, c='k')
        # 标注显著性符号
        plt.text((x1 + x2)*0.5, current_y + y_step*0.12, sign, ha='center', va='bottom', fontsize=12)

    # 调整y轴上限,避免标注超出画布范围
    plt.ylim(df.min().min(), y_start + len(compare_pairs)*y_step + y_step*0.5)
    # ---------- 新增:组间差异p值计算与标注结束 ----------

    plt.title("Read Counts of Individual ENSG")
    plt.xlabel("Samples")
    plt.ylabel("Log Transformed Normalized Read Count")
    plt.savefig(os.path.join(str(save_path), 'all_reads_matrix_violin_plot_norm_log.pdf'))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Create a violin plot from all_reads_matrix.csv')
    parser.add_argument("--in_matrix", help='name of input matrix')
    parser.add_argument("--save_path", help='path to save')
    args = parser.parse_args()
    make_violin(args.in_matrix, args.save_path)

内容的提问来源于stack exchange,提问作者xedahod951

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 20:18:03