2

I have the following equation: y = 1 - cx, where c is a real number. I'm trying to make something where I can pick the range of values for c and plot all the graphs of every function with the corresponding c.

Here's what I got as of now:

p <- ggplot(data = data.frame(x = 0), mapping = aes(x = x))
statfun1 <- c()
for (i in 1:3){
  c <- i
  fun1.i <- function(x){1 - c*x}
  fun1.i.plot <- stat_function(fun = fun1.i, color="red")
  statfun1 <- statfun1 + fun1.i.plot
}
p + statfun1 + xlim(-5, 5)

The p is basically what you need in ggplot2 to plot a function, then I go over in this case the values 1, 2 and 3 for c and I try to add them all at the end but this does not seem to work. Anyone maybe can help me out or put me on the right track?

1 Answer 1

2

Define your function

fun1.i <- function(x, c){1 - c*x}

Now from ?`+.gg`

You can add any of the following types of objects:

...

You can also supply a list, in which case each element of the list will be added in turn.

So you might use lapply

p + xlim(-5, 5) + lapply(1:3, function(c) { 
  stat_function(fun = fun1.i, args = list(c = c), geom = "line", color="red")
  })

Result

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.