【问题标题】:R - difference scatter plotR - 差异散点图
【发布时间】:2016-10-22 17:03:49
【问题描述】:

我想知道是否有一种方法可以在 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)

【问题讨论】:

  • 您只创建了一个情节。阅读构建模拟数据的示例并将代码添加到您的问题主体中,以生成两个与您正在使用的数据集相似的数据集。

标签: r plot scatter


【解决方案1】:

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

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

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

为确保 bin 相同,最好构造一个 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 来计算每个单元格中每个单元格的出现次数。首先,跨箱应用,构建表格(需要使用factor 以确保显示所有级别;如果您的列已经是一个因素,则不需要)。然后,它对其进行简化并构造一个 data.frame,然后使用 mutate 对其进行操作以计算计数差异,然后将其连接回一个表格,该表格为每个 id 提供 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()

从那里,很容易玩弄轴、颜色等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2021-02-06
    • 2016-04-07
    • 2021-04-07
    • 1970-01-01
    相关资源
    最近更新 更多