我想把下面循环生成的代码放在一起:
import scanpy as sc
import seaborn as sns
import matplotlib.pyplot as plt
# Subset the data by condition
conditions = adata_all.obs['condition'].unique()
# Create a grid of subplots with 1 row and 3 columns
fig, axes = plt.subplots(1, 3, figsize=(12, 4), sharex=True, sharey=True)
for i, condition in enumerate(conditions):
adata_sub = adata_all[adata_all.obs['condition'] == condition]
# Run t-SNE
sc.tl.tsne(adata_sub)
# Plot t-SNE with LNP color and condition facet in the appropriate subplot
sc.pl.tsne(adata_sub, color='CD11b', palette=cmap, title=condition, ncols=1, ax=axes[i])
# Save the figure
plt.savefig('tsne_plots.png', dpi=300)
我有三个条件,像这样
conditions: ['AB', 'AC', 'AD']
Categories (3, object): ['AB', 'AC', 'AD'].
但是在输出中只绘制了第一个图,最后两个是空图。有什么问题吗?
正确答案:
import scanpy as sc
import matplotlib.pyplot as plt
# Get unique conditions
conditions = adata_all.obs['condition'].unique()
# Create figure with subplots for each condition
fig, axes = plt.subplots(1, len(conditions), figsize=(12, 4), sharex=True, sharey=True)
# Loop over conditions and plot t-SNE with CD11b color for each
for i, condition in enumerate(conditions):
# Subset data for current condition
adata_sub = adata_all[adata_all.obs['condition'] == condition]
# Compute t-SNE
sc.tl.tsne(adata_sub)
# Plot t-SNE with CD11b color
sc.pl.tsne(adata_sub, color='CD11b', size=10, color_map='turbo', title=condition, show=False, ax=axes[i])
# Save and show the figure
fig.tight_layout()
fig.savefig('tsne_plots.png', dpi=300)
plt.show()