R - 差异散点图

R - difference scatter plot

我想知道是否有一种方法可以在 R 中将两个分箱散点图相互减去。我有两个具有相同轴的分布,我想将一个覆盖在另一个之上并减去它们,从而产生差异散点图。

这是我的两个情节:

和我的情节脚本:

library(hexbin)
library(RColorBrewer)

setwd("/Users/home/")
df <- read.table("data1.txt")
x <-df$c2
y <-df$c3

bin <-hexbin(x,y,xbins=2000)
my_colors=colorRampPalette(rev(brewer.pal(11,'Spectral')))
d <- plot(bin, main=""  , colramp=my_colors, legend=F)

任何关于如何解决这个问题的建议都会很有帮助。

编辑 找到了执行此操作的其他方法:

xbnds <- range(x1,x2)
ybnds <- range(y1,y2)
bin1 <- hexbin(x1,y1,xbins= 200, xbnds=xbnds,ybnds=ybnds)
bin2 <- hexbin(x2,y2,xbins= 200, xbnds=xbnds,ybnds=ybnds)
erodebin1 <- erode.hexbin(smooth.hexbin(bin1))
erodebin2 <- erode.hexbin(smooth.hexbin(bin2))
hdiffplot(erodebin1, erodebin2)

好的,作为起点,这里有一些示例数据。每个都是随机的,其中一个移动到 (2,2)。

df1  <-
  data.frame(
    x = rnorm(1000)
    , y = rnorm(1000)
  )

df2  <-
  data.frame(
    x = rnorm(1000, 2)
    , y = rnorm(1000, 2)
  )

为了确保bins完全相同,最好构造一个hexbin对象。为此,我使用 dplyrbind_rows 来跟踪数据来自哪个 data.frame(如果您有一个 data.frame,这会更容易带有分组变量)。

bothDF <-
  bind_rows(A = df1, B = df2, .id = "df")


bothHex <-
  hexbin(x = bothDF$x
         , y = bothDF$y
         , IDs = TRUE
         )

接下来,我们混合使用 hexbindplyr 来计算每个单元格中每个元素的出现次数。首先,跨箱应用,构建一个 table(需要使用 factor 以确保显示所有级别;如果您的列已经是一个因素则不需要)。然后,它对其进行简化并构造一个 data.frame,然后用 mutate 对其进行操作以计算计数差异,然后再连接回 table,为每个值提供 x 和 y 值身份证号。

counts <-
  hexTapply(bothHex, factor(bothDF$df), table) %>%
  simplify2array %>%
  t %>%
  data.frame() %>%
  mutate(id = as.numeric(row.names(.))
         , diff = A - B) %>%
  left_join(data.frame(id = bothHex@cell, hcell2xy(bothHex)))

head(counts) 给出:

  A B  id diff          x         y
1 1 0   7    1 -1.3794467 -3.687014
2 1 0  71    1 -0.8149939 -3.178209
3 1 0  79    1  1.4428172 -3.178209
4 1 0  99    1 -1.5205599 -2.923806
5 2 0 105    2  0.1727985 -2.923806
6 1 0 107    1  0.7372513 -2.923806

最后,我们使用 ggplot2 绘制结果数据,因为它提供了比 hexbin 本身更多的控制(并且能够更轻松地使用不同的变量而不是算作填充)。

counts %>%
  ggplot(aes(x = x, y = y
             , fill = diff)) +
  geom_hex(stat = "identity") +
  coord_equal() +
  scale_fill_gradient2()

从那里开始,可以很容易地使用坐标轴、颜色等。