在 hexbin 图上添加黄土回归线

问题描述

我一直在尝试寻找在 hexbin 图上添加 loess 回归线的方法。到目前为止我没有任何成功...有什么建议吗?

我的代码如下:

bin<-hexbin(Dataset$a,Dataset$b,xbins=40)

plot(bin,main="Hexagonal Binning",xlab = "a",ylab = "b",type="l")

enter image description here

解决方法

我建议使用 ggplot2 来构建情节。

由于您没有包含任何示例数据,我在下面的示例中使用了 palmerpenguins 包数据集。

library(palmerpenguins) # For the data
library(ggplot2)        # ggplot2 for plotting



ggplot(penguins,aes(x = body_mass_g,y = bill_length_mm)) + 
  geom_hex(bins = 40) + 
  geom_smooth(method = 'loess',se = F,color = 'red') 

reprex package (v0.3.0) 于 2021 年 1 月 5 日创建

,

我没有 base 的解决方案,但可以使用 ggplot 来实现。 base 也应该可以,但是如果您查看 ?hexbin 的文档,您可以看到引用:

请注意,在绘制 hexbin 对象时,使用了 grid 包。您必须使用它的图形(或者如果您知道如何使用来自包点阵的图形)来添加到这样的图中。

我不熟悉如何修改这些。我确实尝试过 ggplotify 将基础转换为 ggplot 并以这种方式进行编辑,但无法将黄土线正确添加到绘图窗口中。

所以这里有一个带有 ggplot 的解决方案,其中包含一些您可以在 Datasets 上尝试的假数据:

library(hexbin) 
library(ggplot2) 

# fake data with a random walk,replace with your data
set.seed(100)
N <- 1000
x <- rnorm(N)
x <- sort(x)
y <- vector("numeric",length=N)
for(i in 2:N){
  y[i] <- y[i-1] + rnorm(1,sd=0.1)
}

# current method
# In documentation for ?hexbin it says:
# "You must use its graphics (or those from package lattice if you know how) to add to such plots."
(bin <- hexbin(x,y,xbins=40))
plot(bin)

# ggplot option. Can play around with scale_fill_gradient to
# get the colour scale similar or use other ggplot options
df <- data.frame(x=x,y=y)
d <- ggplot(df,aes(x,y)) + 
  geom_hex(bins=40) + 
  scale_fill_gradient(low = "grey90",high = "black") +
  theme_bw()
d

# easy to add a loess fit to the data
# span controls the degree of smoothing,decrease to make the line
# more "wiggly"
model <- loess(y~x,span=0.2)
fit <- predict(model)
loess_data <- data.frame(x=x,y=fit)
d + geom_line(data=loess_data,aes(x=x,y=y),col="darkorange",size=1.5)
,

这里有两个选项;您需要决定是要平滑原始数据还是分箱数据。

library(hexbin)
library(grid)

# Some data
set.seed(101)
d <- data.frame(x=rnorm(1000))
d$y <- with(d,2*x^3 + rnorm(1000))

方法 A - 分箱数据

# plot hexbin & smoother : need to grab plot viewport
# From ?hexVP.loess : "Fit a loess line using the hexagon centers of mass 
# as the x and y coordinates and the cell counts as weights."
bin <- hexbin(d$x,d$y)
p <- plot(bin)
hexVP.loess(bin,hvp = p$plot.vp,span = 0.4,col = "red",n = 200)

方法 B - 原始数据

# calculate loess predictions outside plot on raw data
l = loess(y ~ x,data=d,span=0.4)
xp = with(d,seq(min(x),max(x),length=200))
yp = predict(l,xp)

# plot hexbin
bin <- hexbin(d$x,d$y)
p <- plot(bin)

# add loess line
pushHexport(p$plot.vp)
grid.lines(xp,yp,gp=gpar(col="red"),default.units = "native")
upViewport()

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...