如何在热图单元格上使用R语言添加叉号(X)?

我想在热图单元格上添加叉号(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),


         )

```

如何在热图单元格上使用R语言添加叉号(X)?
如何在热图单元格上使用R语言添加叉号(X)?

解决方法:

简便的解决方案是添加带有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()

如何在热图单元格上使用R语言添加叉号(X)?

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

因此,一种替代方法是在相应位置绘制一些线(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,这看起来像

如何在热图单元格上使用R语言添加叉号(X)?

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

np.argwhere(data_masked.T < 0.4)+0.5
上一篇:我如何创建基于热图的值(而不是频率)?


下一篇:c#-Oxyplot:为Oxyplot的热图设置边距/填充