给定一个带有标签 mgroup
的数组 normal_data
,将生成以下热图。
但是,我想知道是否可以使用 Matplotlib 或 Seaborn 有一个 xtick-ytick 颜色条(蓝色、橙色、浅绿色、深蓝色、深绿色的矩形)来表示组成员身份,如图所示上面?
import seaborn as sns
from matplotlib import pyplot as plt
import numpy as np
mgroup=np.array([1,1,1,2,2,3,3,3,3,4,5,5])
normal_data = np.random.randn(12, 12)
ax = sns.heatmap(normal_data, center=0)
plt.show()
最佳答案
您可以使用plt.Rectangle
来绘制彩色矩形。设置clip_on=False
允许在主轴线之外进行绘制。 xaxis transform使用水平方向的 x 坐标,以及 y 方向的轴坐标。 y 轴变换在其他方向上的工作方式类似。
import seaborn as sns
from matplotlib import pyplot as plt
import numpy as np
mgroup = np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 5])
normal_data = np.random.randn(12, 12)
grouping = [3, 2, 4, 1, 2]
colors = ['dodgerblue', 'orange', 'lime', 'darkblue', 'green']
labels = [f'Group {i + 1}' for i in range(len(colors))]
ax = sns.heatmap(normal_data, center=0, cbar_kws={'orientation': 'horizontal', 'pad': 0.08})
for width, pos, color, label in zip(grouping, np.cumsum([0] + grouping), colors, labels):
ax.add_patch(plt.Rectangle((pos, 1.02), width, 0.1, color=color,
clip_on=False, transform=ax.get_xaxis_transform()))
ax.add_patch(plt.Rectangle((1.02, pos), 0.1, width, color=color,
clip_on=False, transform=ax.get_yaxis_transform()))
ax.text(1.14, pos + width/2, label, ha='left', va='center', clip_on=False, transform=ax.get_yaxis_transform())
plt.tight_layout()
plt.show()
关于python - 如何在 Seaborn 或 Matplotplib 中制作组颜色条 xticks yticks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69355430/