Python程序包可将两个热图合二为一(将每个正方形分成两个三角形) [英] Python package to plot two heatmaps in one (split each square into two triangles)

查看:89
本文介绍了Python程序包可将两个热图合二为一(将每个正方形分成两个三角形)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搜索,但是找不到一个简单的解决方案,即通过将热图中的每个正方形都分成两个三角形来绘制两个热图(类似于我在纸上看到的图形).有人知道能够做到这一点的Python包吗?我尝试过seaborn,但我认为实现这一目标没有简单的方法.

I've been searching around but couldn't find an easy solution to plot two heatmaps in one graphic by having each square in the heatmap split into two triangles (similar to the attached graphic I saw in a paper). Does anybody know a Python package that is able to do this? I tried seaborn but I don't think it has an easy way to achieve this.

谢谢您的时间!

-彼得

推荐答案

plt.tripcolor 为三角形的网格着色,类似于 plt.pcolormesh 为矩形网格着色的方式.与 pcolormesh 类似,必须注意,与三角形相比,顶点的行数和列数要少一排.此外,阵列必须设为一维( np.ravel ).将所有这些重新编号为1D可能会有些棘手.

plt.tripcolor colors a mesh of triangles similar to how plt.pcolormesh colors a rectangular mesh. Also similar to pcolormesh, care has to be taken that there is one row and one column of vertices less than there are triangles. Furthermore, the arrays need to be made 1D (np.ravel). All this renumbering to 1D can be a bit tricky.

作为示例,下面的代码根据 x * y mod 10 创建颜色,并为上下三角形使用两个不同的颜色图.

As an example, the code below creates a coloring depending on x*y mod 10 and uses two different colormaps for the upper and the lower triangles.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.tri import Triangulation

M = 30
N = 20
x = np.arange(M + 1)
y = np.arange(N + 1)
xs, ys = np.meshgrid(x, y)
zs = (xs * ys) % 10
zs = zs[:-1, :-1].ravel()

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)]
triang1 = Triangulation(xs.ravel(), ys.ravel(), triangles1)
triang2 = Triangulation(xs.ravel(), ys.ravel(), triangles2)
img1 = plt.tripcolor(triang1, zs, cmap=plt.get_cmap('inferno', 10), vmax=10)
img2 = plt.tripcolor(triang2, zs, cmap=plt.get_cmap('viridis', 10), vmax=10)

plt.colorbar(img2, ticks=range(10), pad=-0.05)
plt.colorbar(img1, ticks=range(10))
plt.xlim(x[0], x[-1])
plt.ylim(y[0], y[-1])
plt.xticks(x, rotation=90)
plt.yticks(y)
plt.show()

PS:要使整数很好地位于单元格的中心(而不是它们的边界),需要进行以下更改:

PS: to have the integer ticks nicely in the center of the cells (instead of at their borders), following changes would be needed:

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

# ...
plt.xlim(x[0]-0.5, x[-1]-0.5)
plt.ylim(y[0]-0.5, y[-1]-0.5)
plt.xticks(x[:-1], rotation=90)
plt.yticks(y[:-1]) 

这篇关于Python程序包可将两个热图合二为一(将每个正方形分成两个三角形)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆