서브 플롯 및 주석을 사용하여 히트 맵에서 xlim 설정
Nov 16 2020
주석과 함께 여러 히트 맵을 나란히 표시하고 싶습니다.
이를 위해 서브 플롯을 사용하고 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
- 씨본 0.9.0
- 파이썬 3.6.5
답변
1 Mr.T Nov 16 2020 at 14:19
먼저 관심 슬라이스를 제공하고 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()
샘플 출력

1 CoMartel Nov 18 2020 at 14:25
이 문제를 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는 도끼 밖에있는 모든 것을 제거합니다