gpt4 book ai didi

python - 如何像使用 R 语言一样在热图单元格上添加十字(X)?

转载 作者:行者123 更新时间:2023-12-02 00:25:07 25 4
gpt4 key购买 nike

我想在热图单元格上添加十字 (X)(取决于显着性水平,但问题在于添加 X)。

就像在 R 语言中一样 (sig.level = XXX)。

查看使用的 Python 和 R 代码以及相应的输出图像。

感谢您的帮助。

# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, center=0, vmin=-1, vmax=1, square=True, linewidths=0.5, fmt=".2f",
cbar_kws={"shrink": .65, "orientation": "horizontal", "ticks":np.arange(-1, 1+1, 0.2)},
annot = True, annot_kws={"weight": 'bold', "size":15})




corrplot(cor(subset (wqw, select =
c(fixed.acidity:quality,ratio.sulfur.dioxide))),
# compute the p matrix
p.mat = cor.mtest(subset
(wqw, select = c(fixed.acidity:quality,ratio.sulfur.dioxide))),
# significance level 0.01
sig.level = 0.01,
# Method to display : color (could be corcle, ...)
method = "color",
# color palette
col = colorRampPalette(c("#BB4444", "#EE9988",
"#FFFFFF", "#77AADD", "#4477AA"))(200),


)

```

python matrix R matrix

最佳答案

简单的解决方案是添加带有 X 形标记的散点图以划掉不需要的单元格。

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt

data = np.random.rand(10,10)
mask = np.zeros_like(data)
mask[np.triu_indices_from(mask)] = True

data_masked = np.ma.array(data, mask=mask)

fig, ax = plt.subplots()
im = ax.imshow(data_masked, cmap="YlGnBu", origin="upper")
fig.colorbar(im)

ax.scatter(*np.argwhere(data_masked.T < 0.4).T, marker="x", color="black", s=100)

plt.show()

enter image description here

这样做的缺点是标记大小(s)与单元格的数量无关,需要针对不同的图形大小进行调整。

因此,另一种方法是在相应位置绘制一些线(X 是两条交叉线)。在这里,我们创建了一个函数 crossout(points, ax=None, scale=1, **kwargs),其中 scale 是线条从每个单元格中所占的百分比。

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

def crossout(points, ax=None, scale=1, **kwargs):
ax = ax or plt.gca()
l = np.array([[[1,1],[-1,-1]]])*scale/2.
r = np.array([[[-1,1],[1,-1]]])*scale/2.
p = np.atleast_3d(points).transpose(0,2,1)
c = LineCollection(np.concatenate((l+p,r+p), axis=0), **kwargs)
ax.add_collection(c)
return c

data = np.random.rand(10,10)
mask = np.zeros_like(data)
mask[np.triu_indices_from(mask)] = True

data_masked = np.ma.array(data, mask=mask)

fig, ax = plt.subplots()
im = ax.imshow(data_masked, cmap="YlGnBu", origin="upper")
fig.colorbar(im)


crossout(np.argwhere(data_masked.T < 0.4), ax=ax, scale=0.8, color="black")


plt.show()

对于 scale=0.8 这看起来像

enter image description here

注意,对于 pcolormesh 图或 seaborn 热图(内部使用 pcolormesh),需要添加 0.5 到数据,即

np.argwhere(data_masked.T < 0.4)+0.5

关于python - 如何像使用 R 语言一样在热图单元格上添加十字(X)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54025615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com