简体   繁体   中英

How to plot an equation changing value of one variable in R using ggplot

I have an equation that gives values between one and zero and would like to use ggplot in R to plot how changing one of the variables (age) in the equation alters the output value. I'd like the X axis to be a range of the variable from 0 to 100 and to plot the output value of the equation on the X axis.

I set the variables passed to the equation like so:

age = 100
d <- (365/4)*age
k <- 5
N <-8
m <- 15000000
Nm <- N*m
p <- 1 - (1 - (1 - (1 - u)^d)^k)^Nm

I am sure there must be a simple way in R to give a range of values for age to pass to the equation and plot the resulting value of P as a line. But I am not sure how best to go about it. Do I need to fill in a table of values in the range beforehand or can I put the range itself within the ggplot command?

Thanks in advance

You can use stat_function .

p <- function(age, u, k, N, m)
{
  1 - (1 - (1 - (1 - u)^((365/4) * age))^k)^(N * m)
}

ggplot(data.frame(age = 1:100), aes(x = age)) + 
  stat_function(fun = p, args = list(u = 0.000005, k = 5, N = 8, m = 15000000)) +
  labs(y = "p")

在此处输入图像描述

There was no variable u defined in the question, but this is a logistic curve, and setting u to 0.000005 puts the middle of your range at p = 0.5, so u is presumably near this value.

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