
image.png
snapatac2中有一副qc圖是這樣的:

image.png
這幅圖是用plotly繪制的,他是用plotly畫的,原函數(shù)長(zhǎng)這樣:
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)
這幅圖感覺(jué)素了點(diǎn),對(duì)于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:
# 計(jì)算 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 的細(xì)胞
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 創(chuàng)建 Kernel 密度估計(jì)圖
sns.kdeplot(
x=np.log10(x), # 對(duì) 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")
# 對(duì) x 軸使用 log scale 并調(diào)整刻度標(biāo)簽
ax.set_xscale('log')
ax.xaxis.set_major_formatter(LogFormatter()) # 使用 LogFormatter 格式化對(duì)數(shù)刻度
# 如果提供了 vline,將其轉(zhuǎn)換為 log10 格式
if vline is not None:
log_vline = np.log10(vline) # 轉(zhuǎn)換為 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()
美化之后,更為清晰。