我想知道是否有办法在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)
Run Code Online (Sandbox Code Playgroud)
关于如何解决这个问题的任何建议都会非常有帮助.
编辑 找到另一种方法:
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)
Run Code Online (Sandbox Code Playgroud)
好吧,作为一个起点,这里有一些样本数据.每个都是随机的,一个转移到(2,2).
df1 <-
data.frame(
x = rnorm(1000)
, y = rnorm(1000)
)
df2 <-
data.frame(
x = rnorm(1000, 2)
, y = rnorm(1000, 2)
)
Run Code Online (Sandbox Code Playgroud)
为确保箱子相同,最好构造一个hexbin
对象.为了实现这一点,我使用dplyr
's bind_rows
来跟踪数据来自哪个data.frame(如果你有一个带有分组变量的data.frame,这会更容易).
bothDF <-
bind_rows(A = df1, B = df2, .id = "df")
bothHex <-
hexbin(x = bothDF$x
, y = bothDF$y
, IDs = TRUE
)
Run Code Online (Sandbox Code Playgroud)
接下来,我们使用混合hexbin
和dplyr
计算每个单元格中每个的出现次数.首先,在整个分档中应用,构建一个表(需要使用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)))
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
最后,我们使用ggplot2
绘制结果数据,因为它提供了更多的控制(以及更容易使用不同的变量而不是计数为填充的能力)hexbin
.
counts %>%
ggplot(aes(x = x, y = y
, fill = diff)) +
geom_hex(stat = "identity") +
coord_equal() +
scale_fill_gradient2()
Run Code Online (Sandbox Code Playgroud)
从那里,很容易玩斧头,颜色等.