尝试了很多种办法:
- colorbar官网文档中的cm.ScalarMappable(norm=norm, cmap=cmap):似乎关联不上数据了……
- 轮廓覆盖和对数色标:这个我生成出来的不能覆盖整个图,周围一圈像是相框一样的留白。而且颜色不是连续的,是分块的。
- 自己写log函数,然后关联ax.colorbar:颜色不是连续的,是分块的。(抄的别人的csdn,找不到了o(╥﹏╥)o)
- 自定义颜色条colorbarBase:这个是关联不上数据的。
最终解决方案:对数色标+连续渐变性
准备三份数据shape=(x,y):要求互相的元素是一一对应的
假设有112个元素,最终我要生成一个形状为14*8的heatmap
def HLA_counts_to_heatmap(data_pos = None, n = 8): # 112/8=14
HLA_count = dict(Counter(data_pos.HLA))
HLA_count = sorted(HLA_count.items(),key=lambda x:x[1],reverse=True)
HLAs, counts = [], []
HLA_temp, count_temp = [], []
i = 0
for item in HLA_count:
i += 1
HLA_temp.append(item[0][4:])
count_temp.append(item[1])
if i == len(HLA_count) or i % n == 0:
print(i, count_temp)
HLAs.append(HLA_temp)
counts.append(count_temp)
if i != 0: HLA_temp, count_temp = [], []
HLAs, counts = np.array(HLAs), np.array(counts)
HLA_count_min = counts[0][0]
HLA_count_max = counts[-1][-1]
assert HLAs.shape == counts.shape
print(HLAs.shape, HLA_count_min, HLA_count_max, [len(m) for m in HLAs], sum([len(m) for m in counts]))
# 获得注释数据
HLA_count = np.zeros((HLAs.shape[0], HLAs.shape[1])).astype(str)
for i in range(HLAs.shape[0]):
for j in range(HLAs.shape[1]):
HLA_count[i, j] = HLAs[i, j] + '\n' + str(counts[i, j])
# 数据log2缩放,使得画图层次更清晰
# from sklearn.preprocessing import StandardScaler, MinMaxScaler, Normalizer, scale
# counts_scaled = scale(counts.reshape(1, -1), axis = 1).reshape(counts.shape)
# counts_scaled = Normalizer().fit_transform(counts.reshape(1, -1)).reshape(counts.shape)
counts_log = np.zeros(counts.shape)
for i in range(counts.shape[0]):
for j in range(counts.shape[1]):
counts_log[i, j] = math.log(counts[i, j], 2)
sum_counts = np.sum(counts) # 所有元素值的和
return HLAs, counts, HLA_count, counts_log, sum_counts
由于参考资料中的内容与问题不符,无法提供具体的解决方案。推荐使用Stack Overflow等技术论坛进行查找相关解决方法。