Skip to main content
 首页 » 编程设计

python之使用 R 或 Python 的二进制数据热图

2025年05月04日8arxive

我有一个由 0 和 1 组成的二进制数据集,其中 0 表示事件不存在,1 表示事件存在。

数据集的样本如下所示:

events    germany    Italy  
Rain      0          1 
hail      1          0 
sunny     0          0 

我想通过从文件中读取数据,以热图的形式获得此数据的红白图片。

请您参考如下方法:

编辑:为了回应下面的评论,这里有一个示例数据文件(在磁盘上保存为“data.txt”):

Rain  0 0 0 0 1 0 1 0 0 1 
Hail  0 1 0 0 0 0 0 1 0 0 
Sunny 1 1 1 0 1 0 1 0 1 1 

在 python 中,我们可以通过以下方式读取标签并绘制此“热图”:

from numpy import loadtxt 
import pylab as plt 
 
labels = loadtxt("data.txt", usecols=[0,],dtype=str) 
A      = loadtxt("data.txt", usecols=range(1,10)) 
 
plt.imshow(A, interpolation='nearest', cmap=plt.cm.Reds) 
plt.yticks(range(A.shape[0]), labels) 
 
plt.show() 
import pylab as plt