snapatac2中有一副qc图是这样的:
这幅图是用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()
美化之后,更为清晰。