1

我对 R 中的“曲线”函数有一个疑问。也许这不是实现我的想法的最佳方式,但我们开始吧。

我试图绘制一个由几个段组成的函数。不同之处在于斜坡。只是为了说明,第一部分类似于 [0,10] 的“y = 1300 - 3.83*x”。根据下面的代码,下一段“y = 1300-4.41*t”将在 [11,20] 上,依此类推。

    seg1 <- function(t) 1300-3.83*t
    curve(seg1, 0, 10, n=1000,xlim=c(0,150),ylim=c(0,1400))
    seg2 <- function(t) 1300-4.41*t
    curve(seg2, 10,20,n=1000,add=TRUE)
    seg3 <- function(t) 1300-5.83*t
    curve(seg3, 20,30,n=4000, add=TRUE)
    seg4 <- function(t) 1300-6.71*t
    curve(seg4, 30,50,n=16000,add=TRUE)
    seg5 <- function(t) 1300-7.71*t
    curve(seg5, 50,100,n=10000,add=TRUE)
    seg6 <- function(t) 1300-8.87*t
    curve(seg6,100,150,n=9000,add=TRUE)

但是,生成的绘图充满了空格。我无法在此处附加它,但我希望像凹集这样的东西,而不是很多带有空格的片段。它应该是连接的。也许这不是在 R 中绘制具有不连续性的函数的最佳方法。

有人可以帮我吗?

4

2 回答 2

0

另一种更灵活的生成点的方法:

segments <- mget(paste0("seg", 1:6)) # A list of functions

ll <- c(0, 10, 20, 30, 50, 100) # Lower limits
ul <- c(10, 20, 30, 50, 100, 150) # Upper limits
k <- length(ll) # Number of segments
n <- 100 # Points per each segment

myfun <- function(ll, ul, n)
  c(mapply(function(s, l, u) s(seq(l, u, length = n)), segments, ll, ul))

plot(y = myfun(ll, ul, n), x = seq(ll[1], ul[k], length = n * k), type = 'l')
于 2015-12-02T18:55:18.490 回答
0

如何生成点而不是使用curve

seg1 <- function(t) 1300-3.83*t
seg2 <- function(t) 1300-4.41*t
seg3 <- function(t) 1300-5.83*t
seg4 <- function(t) 1300-6.71*t
seg5 <- function(t) 1300-7.71*t
seg6 <- function(t) 1300-8.87*t

step <- 0.5 # Smaller for better look but slower to plot
y <- c(seg1(seq(0,10,step)),
       seg2(seq(10,20,step)),
       seg3(seq(20,30,step)),
       seg4(seq(30,50,step)),
       seg5(seq(50,100,step)),
       seg6(seq(100,150,step)))
plot(y, type='l', xlim=c(0,150), ylim=c(0,1400))

编辑:

那么,您的帖子是错误的,但是如果我正确理解您的评论,您需要做的是将代码中的fromand更改to为相同的数字:

seg1 <- function(t) 1300-3.83*t
seg2 <- function(t) 1300-4.41*t
seg3 <- function(t) 1300-5.83*t
seg4 <- function(t) 1300-6.71*t
seg5 <- function(t) 1300-7.71*t
seg6 <- function(t) 1300-8.87*t

curve(seg1, 0, 150, n=1000,xlim=c(0,150),ylim=c(0,1400))
curve(seg2, 0,150,n=1000,add=TRUE)
curve(seg3, 0,150,n=1000, add=TRUE)
curve(seg4, 0,150,n=1000,add=TRUE)
curve(seg5, 0,150,n=1000,add=TRUE)
curve(seg6, 0,150,n=1000,add=TRUE)
于 2015-12-02T18:27:25.123 回答