Hexbin:对每个bin应用功能 [英] Hexbin: apply function for every bin

查看:91
本文介绍了Hexbin:对每个bin应用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个六边形图,其中每个仓位都是绘制落入该仓位的1类和2类点之间的比率(无论是否为对数)。

I would like to build the hexbin plot where for every bin is the "ratio between class 1 and class2 points falling into this bin" is plotted (either log or not).

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

关于如何实施此建议?

Any suggestions on how to implement this? Is there a way to introduce function to every bin based on bin statistics?

推荐答案

@ cryo111的答案具有最重要的成分- ID = TRUE 。之后,只需要弄清楚您要对 Inf 进行什么操作,以及需要多少比例缩放比例来获得整数,从而产生一个漂亮的整数即可。

@cryo111's answer has the most important ingredient - IDs = TRUE. After that it's just a matter of figuring out what you want to do with Inf's and how much do you need to scale the ratios by to get integers that will produce a pretty plot.

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)

这篇关于Hexbin:对每个bin应用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆