用R或Python实现二进制数据的热映射

2024-05-12 23:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

数据集的示例如下:

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

我想通过从一个文件中读取数据,以热图的形式得到这个数据的红白照片。


Tags: 文件数据示例二进制事件读取数据events照片
3条回答

编辑:针对下面的注释,这里有一个示例数据文件(保存在磁盘上为“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

enter image description here

在R中使用Reforme和ggplot2

library(reshape)
library(ggplot2)

dat <- data.frame(weather=c("Rain","Hail","Sunny"), Germany = c(0,1,0), Italy = c(1,0,0))

melt.data<-melt(dat, id.vars="weather", variable_name="country")

qplot(data=melt.data,
      x=country,
      y=weather,
      fill=factor(value),
      geom="tile")+scale_fill_manual(values=c("0"="white", "1"="red"))

enter image description here

?image。用你的数据

dat <- data.matrix(data.frame(Germany = c(0,1,0), Italy = c(1,0,0)))
rownames(dat) <- c("Rain","Hail","Sunny")

这让我们更接近:

image(z = dat, col = c("white","red"))

但更好地处理axis标签会更好。。。尝试:

op <- par(mar = c(5,5,4,2) + 0.1)
image(z = dat, col = c("white","red"), axes = FALSE)
axis(side = 1, labels = rownames(dat), 
     at = seq(0, by = 0.5, length.out = nrow(dat)))
axis(side = 2, labels = colnames(dat), at = c(0,1), las = 1)
box()
par(op)

它给予

binary heatmap

要让heatmap反过来,在datimage(z = t(dat), ....))调用中转换axis(),在第一个调用中将side更改为2,在第二个调用中将1(并将las = 1移动到另一个调用。一、 e.:

op <- par(mar = c(5,5,4,2) + 0.1)
image(z = t(dat2), col = c("white","red"), axes = FALSE)
axis(side = 2, labels = rownames(dat2), 
     at = seq(0, by = 0.5, length.out = nrow(dat2)), las = 1)
axis(side = 1, labels = colnames(dat2), at = c(0,1))
box()
par(op)

相关问题 更多 >