gpt4 book ai didi

r - 在 ggplot 中,在 LOESS 中将 y 限制为 >0

转载 作者:行者123 更新时间:2023-12-03 17:32:32 24 4
gpt4 key购买 nike

这是我的代码:

#data
sites <-
structure(list(site = c(928L, 928L, 928L, 928L, 928L, 928L, 928L,
928L, 928L, 928L, 928L, 928L, 928L, 928L,
928L, 928L, 928L, 928L, 928L, 928L, 928L,
928L, 928L, 928L, 928L, 928L),
date = c(13493L, 13534L, 13566L, 13611L, 13723L,
13752L, 13804L, 13837L, 13927L, 14028L,
14082L, 14122L, 14150L, 14182L, 14199L,
16198L, 16279L, 16607L, 16945L, 17545L,
17650L, 17743L, 17868L, 17941L, 18017L, 18092L),
y = c(7L, 7L, 17L, 18L, 17L, 17L, 10L, 3L, 17L, 24L,
11L, 5L, 5L, 3L, 5L, 14L, 2L, 9L, 9L, 4L, 7L,
6L, 1L, 0L, 5L, 0L)),
.Names = c("site", "date", "y"),
class = "data.frame", row.names = c(NA, -26L))

#convert to date
x<-as.Date(sites$date, origin="1960-01-01")

#plot smooth, line goes below zero!
qplot(data=sites, x, y, main="Site 349")
(p <- qplot(data = sites, x, y, xlab = "", ylab = ""))
(p1 <- p + geom_smooth(method = "loess",span=0.5, size = 1.5))

部分 LOESS线和置信区间低于零,我想将图形限制为 0 和正数(因为负数没有意义)。
enter image description here

我怎样才能做到这一点?

最佳答案

我赞同马特·帕克 (Matt Parker) 的建议,即您必须更改拟合程序。通常适用于仅正数据的一种选择是在对数尺度上进行拟合,然后取幂以获得原始尺度上的结果。这将保证只有正值。

生成具有以下一些问题的随机数据:

 d <- data.frame(x=0:100)
d$y <- exp(rnorm(nrow(d), mean=-d$x/40, sd=0.8))
qplot(x,y,data=d) + stat_smooth()

现在我们可以使用 ggplot 的转换功能对 y 值进行对数转换,但以指数比例显示结果(与原始比例相对应):
qplot(x,y,data=d) + stat_smooth() + scale_y_log10()+coord_trans(ytrans="pow10")

你可以在 coord_trans 上看到这样的例子。帮助页面。如果您不喜欢 y Axis ,则可以操作中断和标签。

根据问题更新进行编辑
ggplot2有一些变化因为这个问题最初是问的,而原来的答案没有处理0。

选项1

解决方案的主要思想是相同的:找到一个变换,将可能值的范围映射到 -Inf 到 Inf,在那里做 loess 平滑,然后对结果进行反向变换。如果没有零,对数转换会很棒。如果包含 0,我认为所需的功能不存在,但通常有效的可能性是 log(1+x)转型。这是内置的,但我们需要进行逆变换 exp(x)-1以及。
library(scales)
#create exp(x)-1 transformation, the inverse of log(1+p)
expm1_trans <- function() trans_new("expm1", "expm1", "log1p")

qplot(x, y, data=sites) + stat_smooth(method="loess") +
scale_y_continuous(trans=log1p_trans()) +
coord_trans(ytrans=expm1_trans())

Loess fit on log(1+x) transformed data

选项 2

第二个选项将评论中的建议扩展到 Matt Parker 的答案:使用包含结果整数性质的回归方法。这意味着计数的过度分散(以防万一)泊松回归。虽然你不能做 loess,但你可以做样条拟合。您可以使用自由度来控制平滑度。
library(splines)
qplot(x, y, data=sites) + stat_smooth(method="glm", family="quasipoisson",
formula = y ~ ns(x, 3))

Spline fit using overdispersed Poisson regression

这两个选项给出了非常相似的结果,这是一件好事。

关于r - 在 ggplot 中,在 LOESS 中将 y 限制为 >0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2777053/

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