【问题标题】:How can I plot a population growth rate function in R?如何在 R 中绘制人口增长率函数?
【发布时间】:2020-07-21 13:11:27
【问题描述】:

我正在尝试在 R 中使用此代码重现图像的情节:

N = 1:100

r = 1

K = 1

r1 = list(r*N*(1 - (N/K)))

plot(N, r1[[1]])

但是负值出现在图上。我做错了什么或如何绘制图像?

提前致谢

【问题讨论】:

  • @Dealec K 是承载能力。 r 是当 N 足够大时降低的增长率。在这种情况下,值是任意的。

标签: r function plot


【解决方案1】:

您可以使用curve 函数,该函数专为绘制函数曲线而设计。这样就避免了提前生成值的弯路。

对于基本曲线,您只需将可变变量 N 编码为 x

curve(expr=r*x*(1 - (x/K)), from=1, to=100)

为了完全重现情节,我们将 R 图形工具箱打开一点。

op <- par(mar=c(4, 8, 2, 5))  ## set margins
curve(r*x*(1 - (x/K)), 1, 100, 
      xlab="", ylab="", xaxt="n", yaxt="n", 
      axes=FALSE, xaxs="i", yaxs="i",
      ylim=c(-8e3, 3e3), lwd=2)
axis(2, labels=FALSE, lwd.ticks=0)
abline(h=-5e3)
text(max(N), -5e3*1.05, "N", font=8, xpd=TRUE)
mtext("r", 2, .5, at=0, las=1, font=8)
mtext("Growth rate", 2, .5, at=2e3, las=1, font=6, cex=1.5)
## for the "K" tick and label in the plot, we need to solve the equation
## to get the intersect with our abitrary x axis at -5e3
f <- function(x, y) r*x*(1 - (x/K)) - y
x.val <- uniroot(f, y=-5e3, lower=0, upper=1000)$root
## and insert the solution as x.value
axis(1, x.val, labels=FALSE, pos=-5e3)
text(x.val, -5e3*1.1, "K", font=8, xpd=TRUE)
par(op)  ## reset margins

结果

【讨论】:

    【解决方案2】:

    如果您查看 r1,您会发现数据绘制正确。值从零开始并减小。

    如果您只是想移动数据以实现快速可视化,您可以添加比例因子:

    #add a scale factor - all values positive
    r2<-r1[[1]]+10000
    plot(N, r2)
    

    #add a scale factor - span y = 0 
    r3<-r1[[1]]+5000
    plot(N, r3)
    

    为绘图添加注释:

    abline(h=0, col="black") #add line at zero
    text(65, -600, "K", cex=1.5, col="black") #add text
    

    【讨论】:

    • 不使用xlab参数如何在这个路口添加K标签??
    猜你喜欢
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    相关资源
    最近更新 更多