【问题标题】:Hexbin: apply function for every binHexbin:为每个 bin 应用函数
【发布时间】:2013-07-16 22:24:05
【问题描述】:

我想构建 hexbin 图,其中为每个 bin 绘制“落入此 bin 的 1 类和 2 类点之间的比率”(无论是对数还是非对数)。

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

关于如何实现这一点的任何建议?有没有办法根据 bin 统计信息为每个 bin 引入函数?

【问题讨论】:

    标签: r data-visualization binning


    【解决方案1】:

    @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)
    

    【讨论】:

    • 嗨!这么晚才回复很抱歉。您的解决方案完全适用于随机数据,但对于真实数据,它具有奇怪的行为 - 即使 bin 包含类 2,它也不会显示原始图像 i42.tinypic.com/nqa8mb.png 和修改后的图像 i42.tinypic.com/5cc5g1.png。这些类是不平衡的,因此一个类不会占用太多的垃圾箱。这种将垃圾箱移到底部的问题可能是什么,但实际的类发生在顶部。
    • @JohnAmraph 我建议尝试将数据过滤成一个可重复的小示例,然后在 OP 中发布该示例 - 我无法从您的描述中真正看出发生了什么
    • 如果我按照我拥有数据的方式编写代码:dt = data.table(x, y, l = c(rep(1,2000),rep(2,8000)), cID = h@cID) 我会收到类似postimg.org/image/ay34ykyfr 的数字,表明索引有问题。我正在尝试找出问题所在...
    • @JohnAmraph 我应该由cID 订购以正确匹配十六进制单元格-我编辑了答案以解决该问题(使用keyby 而不是by
    【解决方案2】:

    您可以通过以下方式确定每个 bin 中 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)
    

    但打印它们是另一回事。例如,如果一个 bin 中没有 2 类点怎么办?那时没有定义分数。 另外,据我了解hexbin 只是一个二维直方图。因此,它计算落入给定 bin 的点数。我认为它不能像您的情况那样处理非整数数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多