【问题标题】:Laying over function onto scatter plot in R将函数放在 R 中的散点图上
【发布时间】:2023-01-01 00:06:08
【问题描述】:

I would like to add the red line

我正在尝试添加一个函数来覆盖我制作的散点图,理想情况下输出类似于图片中涂有红线的输出。我怎样才能在我的散点图中添加一个函数(例如 y=C/ln(x) 形式的函数)?我将调整常量以尝试使其与图像中粗略绘制的其余线条相匹配。

这是我当前的代码,其中 x 和 y 值来自收集的数据表 -

View(DataCollection)
plot(x=DataCollection$`x`, y= DataCollection$`y`,
     xlab = "x",
     ylab = "y",
     xlim = c(0, 2000),
     ylim = c(0, 100),
     pch=20,
     cex=0.2,
     main = "y against x",
)

【问题讨论】:

  • @DAveArmstrong 发布了ggplot2answer。 base-plot 系统中的答案是函数curve

标签: r function rstudio line scatter-plot


【解决方案1】:

下面的代码将估计适当的 C 项,因为 y=C/log(x)y=C*(1/log(x)) 相同,您可以使用 OLS 进行估计。

library(ggplot2)
set.seed(519)
x <- c(runif(90, 10,100), runif(10, 100, 2000))
y <- 2/log(x) + rnorm(100, 0, .05)
dat <- data.frame(x=x, y=y)
ggplot(dat, aes(x=x, y=y)) + 
  geom_point() + 
  geom_smooth(method="lm", formula = y ~ I(1/log(x))-1, col="red", se=FALSE) + 
  theme_classic()

reprex package (v2.0.1) 创建于 2022-12-31

如果你想直接设置C的值,你可以通过设置const来实现:

library(ggplot2)
const <- 2
set.seed(519)
x <- c(runif(90, 10,100), runif(10, 100, 2000))
y <- 2/log(x) + rnorm(100, 0, .05)
dat <- data.frame(x=x, y=y)
dat <- dat[order(dat$x), ]
ggplot(dat, aes(x=x, y=y)) + 
  geom_point() + 
  geom_function(fun = ~const/log(.x), col="red") + 
  theme_classic()

reprex package (v2.0.1) 创建于 2022-12-31

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-03
    • 2016-09-15
    • 1970-01-01
    • 2021-10-29
    • 2019-02-08
    • 2018-03-30
    • 2016-04-07
    • 2014-09-10
    相关资源
    最近更新 更多