Hexbin:对每个区间应用函数

4

我想构建六边形图,其中每个区间都绘制了“落入此区间的类1和类2点之间比率”(对数或非对数)。

x <- rnorm(10000)
y <- rnorm(10000)
h <- hexbin(x,y)
plot(h)
l <- as.factor(c( rep(1,2000), rep(2,8000) ))

有没有关于如何实现这个的建议?是否有一种方法可以根据垃圾箱统计信息为每个垃圾箱引入功能?
2个回答

3

@cryo111的回答拥有最重要的元素 - IDs = TRUE。接下来就只是需要找出你想要如何处理Inf以及需要将比率缩放多少才能得到产生漂亮图形的整数。

library(hexbin)
library(data.table)

set.seed(1)
x = rnorm(10000)
y = rnorm(10000)

h = hexbin(x, y, IDs = TRUE)

# put all the relevant data in a data.table
dt = data.table(x, y, l = c(1,1,1,2), cID = h@cID)

# group by cID and calculate whatever statistic you like
# in this case, ratio of 1's to 2's,
# and then Inf's are set to be equal to the largest ratio
dt[, list(ratio = sum(l == 1)/sum(l == 2)), keyby = cID][,
     ratio := ifelse(ratio == Inf, max(ratio[is.finite(ratio)]), ratio)][,
     # scale up (I chose a scaling manually to get a prettier graph)
     # and convert to integer and change h
     as.integer(ratio*10)] -> h@count

plot(h)

enter image description here


嗨!抱歉回复晚了。你的解决方案对于随机数据完全有效,但是对于真实数据,它会出现奇怪的行为 - 即使箱子包含类别2,也不会显示原始图像http://i42.tinypic.com/nqa8mb.png和修改后的图像http://i42.tinypic.com/5cc5g1.png。类别不平衡,因此并不会有太多的箱子被一个类占据。这种将箱子移动到底部但实际类别出现在顶部的问题可能是什么? - John Amraph
@JohnAmraph 我建议您尝试将数据过滤到一个小的可重现的示例,并将该示例发布在 OP 中 - 从您的描述中我无法真正了解发生了什么。 - eddi
如果我按照数据的方式编写代码:dt = data.table(x, y, l = c(rep(1,2000),rep(2,8000)), cID = h@cID),我会得到如下图所示的结果http://postimg.org/image/ay34ykyfr/,表明索引存在问题。我正在努力找出问题所在... - John Amraph
@JohnAmraph 我应该按照 cID 排序以正确匹配六边形单元格 - 我编辑了答案来修复这个问题(使用 keyby 而不是 by)。 - eddi

1
你可以通过以下方式确定每个箱中的1类和2类点数:
library(hexbin)
library(plyr)
x=rnorm(10000)
y=rnorm(10000)
#generate hexbin object with IDs=TRUE
#the object includes then a slot with a vector cID
#cID maps point (x[i],y[i]) to cell number cID[i]
HexObj=hexbin(x,y,IDs = TRUE)

#find count statistics for first 2000 points (class 1) and the rest (class 2)
CountDF=merge(count(HexObj@cID[1:2000]),
              count(HexObj@cID[2001:length(x)]),
              by="x",
              all=TRUE
             )
#replace NAs by 0
CountDF[is.na(CountDF)]=0
#check if all points are included
sum(CountDF$freq.x)+sum(CountDF$freq.y)

但是打印它们又是另一回事。例如,如果一个箱子中没有2级点,那么该分数就没有定义。 此外,据我所知,hexbin只是一个二维直方图。因此,它计算落入给定箱子中的点的数量。我不认为它可以处理您的情况中的非整数数据。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接