gpt4 book ai didi

r - 在 ggplot2 中制作的 stat_summary_hex 图之间的操作

转载 作者:行者123 更新时间:2023-12-02 09:24:06 24 4
gpt4 key购买 nike

我有两个空间分布的群体 A 和 B,其中一个字符 Z,我希望能够制作一个 hexbin 减去每个 hexbin 中字符的比例。这里我有两个理论种群 A 和 B 的代码

library(hexbin)
library(ggplot2)

set.seed(2)
xA <- rnorm(1000)
set.seed(3)
yA <- rnorm(1000)
set.seed(4)
zA <- sample(c(1, 0), 20, replace = TRUE, prob = c(0.2, 0.8))
hbinA <- hexbin(xA, yA, xbins = 40, IDs = TRUE)

A <- data.frame(x = xA, y = yA, z = zA)

set.seed(5)
xB <- rnorm(1000)
set.seed(6)
yB <- rnorm(1000)
set.seed(7)
zB <- sample(c(1, 0), 20, replace = TRUE, prob = c(0.4, 0.6))
hbinB <- hexbin(xB, yB, xbins = 40, IDs = TRUE)

B <- data.frame(x = xB, y = yB, z = zB)


ggplot(A, aes(x, y, z = z)) + stat_summary_hex(fun = function(z) sum(z)/length(z), alpha = 0.8) +
scale_fill_gradientn(colours = c("blue","red")) +
guides(alpha = FALSE, size = FALSE)

ggplot(B, aes(x, y, z = z)) + stat_summary_hex(fun = function(z) sum(z)/length(z), alpha = 0.8) +
scale_fill_gradientn (colours = c("blue","red")) +
guides(alpha = FALSE, size = FALSE)

这是两个结果图

Graph of population A

Graph of population B

我的目标是用 hexbins 制作第三张图,其中 hexbins 之间的差值在相同坐标下,但我什至不知道如何开始做,我在光栅包中做了类似的事情,但是我需要它作为 hexbins

非常感谢

最佳答案

您需要确保两个图使用完全相同的分箱。为了实现这一点,我认为最好事先进行分箱,然后用 stat_identity/geom_hex 绘制结果。使用代码示例中的变量,您可以:

## find the bounds for the complete data 
xbnds <- range(c(A$x, B$x))
ybnds <- range(c(A$y, B$y))
nbins <- 30

# function to make a data.frame for geom_hex that can be used with stat_identity
makeHexData <- function(df) {
h <- hexbin(df$x, df$y, nbins, xbnds = xbnds, ybnds = ybnds, IDs = TRUE)
data.frame(hcell2xy(h),
z = tapply(df$z, h@cID, FUN = function(z) sum(z)/length(z)),
cid = h@cell)
}

Ahex <- makeHexData(A)
Bhex <- makeHexData(B)

## not all cells are present in each binning, we need to merge by cellID
byCell <- merge(Ahex, Bhex, by = "cid", all = T)

## when calculating the difference empty cells should count as 0
byCell$z.x[is.na(byCell$z.x)] <- 0
byCell$z.y[is.na(byCell$z.y)] <- 0

## make a "difference" data.frame
Diff <- data.frame(x = ifelse(is.na(byCell$x.x), byCell$x.y, byCell$x.x),
y = ifelse(is.na(byCell$y.x), byCell$y.y, byCell$y.x),
z = byCell$z.x - byCell$z.y)

## plot the results

ggplot(Ahex) +
geom_hex(aes(x = x, y = y, fill = z),
stat = "identity", alpha = 0.8) +
scale_fill_gradientn (colours = c("blue","red")) +
guides(alpha = FALSE, size = FALSE)

ggplot(Bhex) +
geom_hex(aes(x = x, y = y, fill = z),
stat = "identity", alpha = 0.8) +
scale_fill_gradientn (colours = c("blue","red")) +
guides(alpha = FALSE, size = FALSE)

ggplot(Diff) +
geom_hex(aes(x = x, y = y, fill = z),
stat = "identity", alpha = 0.8) +
scale_fill_gradientn (colours = c("blue","red")) +
guides(alpha = FALSE, size = FALSE)

关于r - 在 ggplot2 中制作的 stat_summary_hex 图之间的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39296198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com