如何将 spline() 与 ggplot 一起使用?

发布于 2024-10-08 17:14:29 字数 297 浏览 0 评论 0原文

我想使用样条线(y~x)来拟合我的数据,但我能找到的所有示例都使用带有平滑功能的样条线,例如 lm(y~ns(x), df=_)。

我想专门使用 spline() ,因为我使用它来进行我正在制作的图所表示的分析。

有没有一种简单的方法在 ggplot 中使用 spline() ?

我已经考虑过使用拟合线的黑客方法

geom_smooth(aes(x=(spline(y~x)$x, y=spline(y~x)$y))

,但我不想诉诸于此。

谢谢!

I would like to fit my data using spline(y~x) but all of the examples that I can find use a spline with smoothing, e.g. lm(y~ns(x), df=_).

I want to use spline() specifically because I am using this to do the analysis represented by the plot that I am making.

Is there a simple way to use spline() in ggplot?

I have considered the hackish approach of fitting a line using

geom_smooth(aes(x=(spline(y~x)$x, y=spline(y~x)$y))

but I would prefer not to have to resort to this.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

握住我的手 2024-10-15 17:14:29

这是你想要的吗?

n <- 10
d <- data.frame(x = 1:n, y = rnorm(n))
ggplot(d,aes(x,y)) + geom_point() + 
  geom_line(data=data.frame(spline(d, n=n*10)))

is this what you want?

n <- 10
d <- data.frame(x = 1:n, y = rnorm(n))
ggplot(d,aes(x,y)) + geom_point() + 
  geom_line(data=data.frame(spline(d, n=n*10)))
千笙结 2024-10-15 17:14:29

或者,使用 ggformula https://rdrr.io/cran /ggformula/man/geom_spline.html,您可以直接在ggplot()内调用ggformula::stat_spline()

library(ggplot2)
library(ggformula)

n<-1000
d <- data.frame(x = 1:n, y = rnorm(n))
ggplot(d,aes(x,y))+
  # geom_point()+
  stat_spline()

输入图片此处描述

注意:OP 特别询问了有关使用 spline() 的问题。 stat_spline() {ggformula} 调用 smooth.spline() {stats},这可能与 spline() {stats} 的实现不完全相同code> 但认为对其他人来说这可能仍然是一个有用的答案。

Alternatively, with ggformula https://rdrr.io/cran/ggformula/man/geom_spline.html, you can call ggformula::stat_spline() directly within ggplot().

library(ggplot2)
library(ggformula)

n<-1000
d <- data.frame(x = 1:n, y = rnorm(n))
ggplot(d,aes(x,y))+
  # geom_point()+
  stat_spline()

enter image description here

Note: OP asked specifically about using spline(). stat_spline() {ggformula} calls smooth.spline() {stats}, which might not be exactly the same implementation as spline() {stats} but think it may still be a useful answer here for others.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文