最小化R图中彼此堆叠的曲线之间的距离

时间:2017-12-07 18:48:01

标签: r function plot polygon

我有一个R函数,用于绘制堆叠在一起的曲线(参见代码下面的图片)。

然而,我想知道如何调整曲线之间的距离(s ee蓝色箭头),这样曲线看起来不那么平坦? / p>

此外,是否可以使用polygon代替lines来绘制这些曲线?

stacked = function(a, b, lo, hi, d, Bi = 55, n = 1e2){

h = list()

for(i in 1:length(d)){
         p = function(x) get(d[i])(x, a, b)
     prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
likelihood = function(x) dbinom(Bi, n, x)
 posterior = function(x) prior(x)*likelihood(x)
      h[i] = list(curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n", n = 1e3))
}
plot(matrix(c(rep(c(.4, .8), each = length(d))), length(d), 2), rep(1:length(d), 2), ty = "n", xlim = 0:1, ann = FALSE, xaxt = "n", ylim = c(1, length(d)+.4))

for(i in 1:length(d)){
lines(h[[i]]$x, h[[i]]$y+i, ty = "l", xpd = NA, col = i)
  }
}
# Example of use:
stacked(lo = 0, hi = 1, a = 2, b = 3, d = c("dgamma", "dnorm", "dcauchy", "dbeta", "dlogis", "dweibull"))

enter image description here

1 个答案:

答案 0 :(得分:3)

您可以在绘制线条之前缩放y值。我在您的函数中添加了scale参数。尝试scale = 2或3

stacked = function(a, b, lo, hi, d, Bi = 55, n = 1e2, scale=1){

    h = list()
    for(i in 1:length(d)) {
             p = function(x) get(d[i])(x, a, b)
         prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
    likelihood = function(x) dbinom(Bi, n, x)
     posterior = function(x) prior(x)*likelihood(x)
          h[i] = list(curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n", n = 1e3))
    }
    plot(matrix(c(rep(c(.4, .8), each = length(d))), length(d), 2), rep(1:length(d), 2), ty = "n", xlim = 0:1, ann = FALSE, xaxt = "n", ylim = c(1, length(d)+.4))

    for(i in 1:length(d)){
        lines(h[[i]]$x, scale*h[[i]]$y+i, ty = "l", xpd = NA, col = i)
      }
}

stacked(lo = 0, hi = 1, a = 2, b = 3, scale=2,
    d = c("dgamma", "dnorm", "dcauchy", "dbeta", "dlogis", "dweibull"))

如果您希望填写曲线下方的区域,可以使用polygon。改变行:

for(i in 1:length(d)){
        lines(h[[i]]$x, scale*h[[i]]$y+i, ty = "l", xpd = NA, col = i)
      }

for(i in 1:length(d)){
    polygon(x=h[[i]]$x, y=scale*h[[i]]$y+i, col = i)
  }