【问题标题】:Set xlim in heatmap with subplots and annotation使用子图和注释在热图中设置 xlim
【发布时间】:2020-11-16 11:33:19
【问题描述】:

我想并排绘制几个热图,并带有注释。

为此,我使用子图,并且可以使用 ax kwarg 在其轴上绘制每个热图。

问题是当我使用 xlim 时:它应用于热图,而不是注释:

代码如下:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

values = np.random.random((7,24)) # create (7,24) shape array 

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(30,10)) # create 2 columns for subplots

ax1 = sns.heatmap(values, annot=True, ax=ax1) # heatmap with annotation

ax1.set(xlim=(12,22)) # works fine with this line commented
# ax1.set_xlim(12,22)

# ax2 = sns.heatmap(values, annot=True, ax=ax2) # second heatmap

plt.show()

第二个热图会变得更糟,因为第二个热图的注释绘制在第一个热图上。

如何在使用注释时将 x 轴限制为 (12,22)?

  • matplotlib 2.2.2
  • seaborn 0.9.0
  • python 3.6.5

【问题讨论】:

  • 为什么不屏蔽不想包含的热图部分而不是设置 xlim?有关一般方法,请参见此处:stackoverflow.com/a/64801510/8881141
  • 添加蒙版确实是一个可行的解决方案,但感觉像是一种解决方法,需要额外的步骤,因为您需要创建蒙版并设置 xlim 以使其正常工作。我更喜欢一个不那么“hacky”的解决方案:)
  • 你开过bug票吗? github.com/mwaskom/seaborn
  • 不,但是 seaborn 现在是 0.11,所以可能已经修复了。在提交票证之前,我必须检查一下。同时,我会接受你的回答
  • 谢谢,我发了一张bug票(github.com/mwaskom/seaborn/issues/2358

标签: python matplotlib seaborn


【解决方案1】:

在seaborn github上发布这个问题后,这是官方的答案:

matplotlib 文本对象在被剪裁时不会被自动剪裁 放置在轴限制之外;你可以通过传递来打开它 不过,annot_kws=dict(clip_on=True) 到热图。

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

values = np.random.random((7,24)) # create (7,24) shape array 

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(30,10)) # create 2 columns for subplots

ax1 = sns.heatmap(values, annot=True, ax=ax1, annot_kws=dict(clip_on=True)) # heatmap with annotation

ax1.set(xlim=(12,22)) # works fine with this line commented
# ax1.set_xlim(12,22)

ax2 = sns.heatmap(values, annot=True, ax=ax2, annot_kws=dict(clip_on=True)) # second heatmap
ax2.set(xlim=(12,22))

plt.show()

clip_on=True 将删除斧头之外的所有内容

【讨论】:

  • 非常有趣。对于未来的读者,如果将其中一个子图设置为 clip_on=False 以强调差异,可能会更有启发性。尴尬的是,我应该知道基于我得到的previous answer 的解决方案。
【解决方案2】:

为什么不首先提供感兴趣的切片并重新标记 x 轴?

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

np.random.seed(1234)
values = np.random.random((7,24)) # create (7,24) shape array # create (7,24) shape array ) # create (7,24) shape array 

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(21,7)) # create 2 columns for subplots

#full heatmap
sns.heatmap(values, annot=True, ax=ax1) 

#slice of interest
start=12
stop=22
sns.heatmap(values[:, start:stop+1], annot=True, ax=ax2, xticklabels = np.arange(start, stop+1)) # second heatmap

plt.show()

示例输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-02
    • 2013-03-29
    • 1970-01-01
    • 2021-12-08
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多