R - 差异散点图

标签 r plot scatter

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

这是我的两个情节:

enter image description here enter image description here

和我的情节脚本:

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

为确保 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计算每个单元格中每个的出现次数。首先,跨 bin 应用,构建一个表格(需要使用 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()

enter image description here

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

关于R - 差异散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40194765/

相关文章:

python - NLTK 情感维德 : build pie chart with scores

python - Pandas 散点图 : Indices Out-of-Bounds

Python 散点图 - 如何查看每个点的条目数

在 R 中重构数据框架

r - 如何计算具有共同列名的不同数据框之间的差异

python - 是否有与 R 中的 smooth.spline 函数等效的 Python

python - 加速 matplotlib 散点图

java - 如何将 R 脚本加载到 JRI 并从 Java 执行?

matlab - 如何创建一个表示没有循环的正弦曲线总和的图?

r - 我可以将屏幕上的绘图写入文件吗?