【问题标题】:How to create Lines connecting two points in R如何在R中创建连接两点的线
【发布时间】:2016-04-12 00:36:16
【问题描述】:

有没有办法在 R 中创建连接两点的线? 我知道lines(),函数,但它创建了我正在寻找的线段是一条无限长的线。

【问题讨论】:

标签: r graphics visualization lines


【解决方案1】:

使用segment()函数。

#example    
x1 <- stats::runif(5)
x2 <- stats::runif(5)+2
y <- stats::rnorm(10)


plot(c(x1,x2), y)


segments(x1, y[1:5], x2, y[6:10], col= 'blue')

【讨论】:

  • 谢谢,但我不是在寻找片段。
  • 为什么不想要细分?
【解决方案2】:

这是玛莎建议的一个例子:

set.seed(1)
x <- runif(2)
y <- runif(2)

# function
segmentInf <- function(xs, ys){
  fit <- lm(ys~xs)
  abline(fit)
}

plot(x,y)
segmentInf(x,y)

【讨论】:

  • 谢谢,我相信像这样创建一个自定义函数是最好的解决方案。可能 R 没有任何这样的预定义函数。
  • 我投了赞成票,但我现在的等级是 11。一旦我达到 15 岁,投票将生效。
【解决方案3】:
#define x and y values for the two points
x <- rnorm(2)
y <- rnorm(2)
slope <- diff(y)/diff(x)
intercept <- y[1]-slope*x[1]
plot(x, y)
abline(intercept, slope, col="red")
# repeat the above as many times as you like to satisfy yourself

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2021-08-22
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多