Skip to main content
 首页 » 编程设计

python之热图中的标签组

2024年10月25日10mengfanrong

我有一个数组,其中第 ij 个条目是 i 和 j 区域共有的基因数,这些基因在 < em>i 相对于 j。

标记每个 xtick 和 ytick 会使图形过于拥挤。如同 this question和 this question我想在我的 x 轴上对标签进行分组。

下图中来自 Hawrylycz 等人 (2012) 的热图的 xticklabels 是我想要的一个很好的例子 xticklabels 指的是更一般的区域。例如,额叶下的所有列都对应于额叶内大脑中的结构。

我不是要复制 yticklabels 或条形图插图。

我的方法

对于热图中的每个框,我都有一个本体。我选择绘制几个区域的结构,例如仅“额叶和顶叶”。

使用本体,我可以发现每个结构的列组的开始和结束索引。 如何使用这些索引来绘制组标签?

请您参考如下方法:

像这样:

import pandas as pd 
from numpy.random import random_integers 
from numpy import reshape 
import matplotlib.pyplot as plt 
from matplotlib.ticker import FixedLocator, FixedFormatter 
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 
lalph = list(alph.lower()) 
alph = list(alph) 
 
df = pd.DataFrame(random_integers(0,100,(26,26)),columns=alph, 
                  index=lalph) 
 
# Two lines just to make a plaid image in imshow  
differ = reshape([sum(df[col2]-df[col]) for col2 in df for col in df], (26,26)) 
differ = pd.DataFrame(differ, columns=alph,index=alph) 
 
# pick the labels you want 
ticks = [2, 14, 18, 19, 22] # C=2 because A=0 because Python is 0-indexed 
ticklabels = [alph[x] for x in ticks] 
 
fig = plt.figure(figsize=(3,5)) 
ax = fig.add_subplot(111) 
ax.imshow(differ) 
ax.autoscale(False) 
 
# display only the chosen ticks and ticklabels 
ax.xaxis.set_major_locator(FixedLocator(ticks)) 
ax.xaxis.set_major_formatter(FixedFormatter(ticklabels)) 

您将拥有一个字符串命名基因列表,而不是用作字母列表的字符串,但 imshow 轴索引仍然是底层 numpy 数组的索引。