我正在尝试绘制一个带有自定义位置和两个轴上的标签的海洋热图。数据框如下所示:
我可以用seaborn.heatmap
正常绘制:
fig, ax = plt.subplots(figsize=(8, 8))
sns.heatmap(genome_freq.applymap(lambda x: np.log10(x+1)),
ax=ax)
plt.show()
我有一个要设置为xticks(binned_chrom_genome_pos
)的职位列表:
[1000000, 248000000, 491000000, 690000000, 881000000, 1062000000, 1233000000, 1392000000, 1538000000, 1679000000, 1814000000, 1948000000, 2081000000, 2195000000, 2301000000, 2402000000, 2490000000, 2569000000, 2645000000, 2709000000, 2772000000, 2819000000, 2868000000, 3023000000]
但是,当我尝试修改xticks时,图变为空:
plt.xticks(binned_chrom_genome_pos)
我还注意到x轴标签与指定的刻度不对应。
有人可以帮助我正确绘制吗?
答案 0 :(得分:0)
ax.get_xticks()
返回刻度线的位置。您可以看到它们在0.5到3000之间。这些值引用数据的索引。由plt.xticks
或ax.set_xticks
设置的较大值仍被解释为数据索引。因此,如果您有10行数据,并将xticks
设置为[0, 1000]
,则图中的数据将仅占据x范围的1%,因此消失。我不确定自己是否要弄清楚,所以我将举一个综合数据示例:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
#generating data
dic = {a:np.random.randint(0,1000,100) for a in range(0,1000000, 10000)}
genome_freq = pd.DataFrame(dic, index=range(0,1000000, 10000))
#plotting heatmaps
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))
sns.heatmap(genome_freq.applymap(lambda x: np.log10(x+1)),
ax=ax1)
sns.heatmap(genome_freq.applymap(lambda x: np.log10(x+1)),
ax=ax2)
old_ticks = ax2.get_xticks()
print(np.min(old_ticks), np.max(old_ticks), len(old_ticks)) # prints 0.5 99.5 34
ax2.set_xticks([0,300]) # setting xticks with values way larger than your index squishes your data
plt.show()
因此,您要做的是根据数据大小更改xticks,然后覆盖xticklabels
:
给出您问题中的新标签:
new_labels = [1000000, 248000000, 491000000, 690000000, 881000000, 1062000000, 1233000000, 1392000000, 1538000000, 1679000000, 1814000000, 1948000000, 2081000000, 2195000000, 2301000000, 2402000000, 2490000000, 2569000000, 2645000000, 2709000000, 2772000000, 2819000000, 2868000000, 3023000000]
len(new_labels) # returns 24
fig, ax = plt.subplots(figsize=(4, 4))
sns.heatmap(genome_freq.applymap(lambda x: np.log10(x+1)),
ax=ax)
因此,现在我们希望在前最小值和前最大值之间有24个均匀间隔的xticks。我们可以使用np.linspace
来实现:
old_ticks = ax.get_xticks()
new_ticks = np.linspace(np.min(old_ticks), np.max(old_ticks), len(new_labels))
ax.set_xticks(new_ticks)
ax.set_xticklabels(new_labels)
plt.show()