【问题标题】:Use matplotlib to plot a heat map with split diagonal使用 matplotlib 绘制具有分割对角线的热图
【发布时间】:2020-11-08 03:01:00
【问题描述】:

我想用matplotlib制作一个同时表示两个对称矩阵的热图,比如A和B,这样对角线上方的方块将根据A中的元素着色,对角线下方的方块将根据B中的元素着色。

有两件事我不知道该怎么做:

  1. 对角线中的正方形应该穿过对角线分割,这样上面的三角形根据A中的对角线元素着色,下面的三角形根据B中的对角线元素着色。如何做到这一点?

  2. 应为 A 和 B 使用两个单独的颜色图,因为 A 和 B 中值的范围是完全不同的。如何将两个颜色图应用于同一个热图?一个相关的问题是如何放置两个对应的颜色条,一个在热图的右侧,一个在热图的底部,一个在 B 的底部。

任何帮助将不胜感激。

【问题讨论】:

标签: matplotlib heatmap


【解决方案1】:

我也有类似的需求,关注了Python package to plot two heatmaps in one (split each square into two triangles),并尝试根据我的需要进行修改。

在我下面的代码中,我的 x 轴应该是 SOMA 值列表,y 轴应该是 Q 值列表。 QPrecision 和 Precision 是我在单元格的两个三角形中表示的两个不同的值。可以通过将位置属性更改为“底部”或“顶部”来修改颜色条的位置。 我注意到的一件事是 PyCharm 无法正确显示图形,但保存的图像看起来像附加的图像

M = len(SOMA)
N = len(Q)
x = np.arange(M + 1)
y = np.arange(N + 1)

xs, ys = np.meshgrid(x, y)

zs1 = result['PRECISION']
zs2 = result['QPRECISION']
zs1 = zs1.astype(dtype=float)
zs2 = zs2.astype(dtype=float)



triangles1 = [(i + j*(M+1), i+1 + j*(M+1), i + (j+1)*(M+1)) for j in range(N) for i in range(M)]
triangles2 = [(i+1 + j*(M+1), i+1 + (j+1)*(M+1), i + (j+1)*(M+1)) for j in range(N) for i in range(M)]
print(np.shape(triangles1))
print(np.shape(triangles2))
fig = plt.figure()
ax = fig.add_subplot(111)

triang1 = Triangulation(xs.ravel(), ys.ravel(), triangles1)
triang2 = Triangulation(xs.ravel(), ys.ravel(), triangles2)

newcmp = ListedColormap(['#DAFFAC','#8FFD03'])

img1 = ax.tripcolor(triang1, zs1, cmap=plt.get_cmap('Blues'))
img2 = ax.tripcolor(triang2, zs2, cmap=plt.get_cmap(newcmp))


  
cb1 = plt.colorbar(img2, ax=[ax], ticks=[5, 4] , location='left',label='Q based Precision', pad=0.15)
cb2 = plt.colorbar(img1, ax=[ax], ticks=[5, 4, 3, 2, 1, 0],location='right',label='Suppported Precision', pad =0.05)
   
   
labels = np.arange(4, int(5) + 1, 1)
cb1.set_ticks([4.25, 4.75])
cb1.set_ticklabels(labels)

for tick in ax.xaxis.get_majorticklabels():
    tick.set_horizontalalignment("center")


plt.xlim(x[0], x[-1])
plt.ylim(y[0], y[-1])
plt.xlabel("SOMA")
plt.ylabel("Q")

x = np.arange(0.5,22,1) #range of SOMA
y = np.arange(0.5,14,1) #range of Q

plt.xticks(x, SOMA, rotation=90)
plt.yticks(y, Q)
plt.title(PLOT_TITLE)
plt.savefig('fig.png',bbox_inches='tight')

plt.show()

Sample Output Image

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2018-11-23
    • 2020-03-31
    • 2014-04-01
    • 2019-10-21
    • 2018-02-08
    • 1970-01-01
    相关资源
    最近更新 更多