2024-09-28 snapatac2 qc图美化

image.png

snapatac2中有一副qc图是这样的:


image.png

这幅图是用plotly绘制的,他是用plotly画的,原函数长这样:

def tsse(
    adata: AnnData,
    min_fragment: int = 500,
    width: int = 500,
    height: int = 400,
    **kwargs,
) 
    if "tsse" not in adata.obs:
        logging.info("Computing TSS enrichment score...")
        snapatac2.metrics.tsse(adata, inplace=True)

    selected_cells = np.where(adata.obs["n_fragment"] >= min_fragment)[0]
    x = adata.obs["n_fragment"][selected_cells]
    y = adata.obs["tsse"][selected_cells]

    fig = kde2d(x, y, log_x=True, log_y=False)
    fig.update_layout(
        xaxis_title="Number of unique fragments",
        yaxis_title="TSS enrichment score",
    )

    return render_plot(fig, width, height, **kwargs)

这幅图感觉素了点,对于plotly熟悉程度不如matplotlib,seaborn,所以我就想用自己熟悉的方式美化一下。

import snapatac2 as sa2
import pandas as pd
import numpy as np
import os
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from anndata import AnnData
import logging
from matplotlib.ticker import LogFormatter
import scanpy as sc


def tsse_seaborn(
    adata: AnnData,
    min_fragment: int = 500,
    width: int = 5,
    height: int = 4,
    vline: float | None = None,  # Vertical line at unique fragment number
    hline: float | None = None,  # Horizontal line at TSS enrichment score
    **kwargs
) -> plt.Figure | None:
    # 计算 TSS enrichment score 如果不存在
    if "tsse" not in adata.obs:
        logging.info("Computing TSS enrichment score...")
        sa2.metrics.tsse(adata, inplace=True)

    # 筛选满足 n_fragment >= min_fragment 的细胞
    selected_cells = np.where(adata.obs["n_fragment"] >= min_fragment)[0]
    x = adata.obs["n_fragment"][selected_cells]
    y = adata.obs["tsse"][selected_cells]

    fig, ax = plt.subplots(figsize=(width, height))
    
    # 使用 Seaborn 创建 Kernel 密度估计图
    sns.kdeplot(
        x=np.log10(x),  # 对 x 轴使用 log10
        y=y,
        cmap="viridis",
        shade=True,
        cbar=True,
        ax=ax
    )
    
    ax.set_xlabel("Number of unique fragments")
    ax.set_ylabel("TSS enrichment score")
  

    # 对 x 轴使用 log scale 并调整刻度标签
    ax.set_xscale('log')
    ax.xaxis.set_major_formatter(LogFormatter())  # 使用 LogFormatter 格式化对数刻度

    # 如果提供了 vline,将其转换为 log10 格式
    if vline is not None:
        log_vline = np.log10(vline)  # 转换为 log10 格式
        ax.axvline(x=log_vline, color='red', linestyle='--', label=f'Unique fragments at {vline}')

    # 如果提供了 hline,直接绘制
    if hline is not None:
        ax.axhline(y=hline, color='red', linestyle='--', label=f'TSS enrichment score at {hline}')

    # 如果任意一条线被绘制,添加图例
    if vline is not None or hline is not None:
        ax.legend()

    return fig

# 使用示例:
# fig = tsse_seaborn(adata, min_fragment=500, width=10, height=8, vline=1000, hline=2.5)
# plt.show()

美化之后,更为清晰。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容