简体   繁体   中英

How can I plot a population growth rate function in R?

I'm trying to reproduce the plot of the image using this code in R:

N = 1:100

r = 1

K = 1

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

plot(N, r1[[1]])

but negative values appear on the graph. What am I doing wrong or how can I graph the image?

增长率

Thanks in advance

You could use the curve function, which is designed for drawing function curves. In this way, you avoid the detour of generating values in advance.

For the basic curve you just need to code your varying variable N as x :

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

To completely reproduce the plot, we open the R graphics toolbox a little further.

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

Result

在此处输入图像描述

If you have a look at r1, you'll see that the data are plotted correctly. The values begin at zero and decrease.

If you simply wanted to shift the data for a quick visualization, you can add a scale factor:

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

or

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

Add annotation to the plot:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM